Home >Backend Development >Golang >How to perform data type conversion in golang

How to perform data type conversion in golang

青灯夜游
青灯夜游Original
2022-11-22 18:38:056633browse

There is no implicit type conversion in golang. All type conversions must be explicitly declared with the syntax "valueOfTypeB = typeB(valueOfTypeA)". Type conversion can only be successful if the definition is correct. When converting from a type with a larger value range to a type with a smaller value range, precision loss (truncation) will occur.

How to perform data type conversion in golang

The operating environment of this tutorial: windows10 system, GO 1.11.2, thinkpad t480 computer.

Go language data type conversion

Type conversion occurs when a value is converted from one type to another. Static languages ​​such as c/c and Java provide implicit type conversion, but this is different for a strong type system like golang. Golang does not support automatic type conversion or implicit type conversion.

Since there is no implicit type conversion in Go language, all type conversions must be explicitly declared:

valueOfTypeB = typeB(valueOfTypeA)

means: The value of type B = type B (value of type A)

Example:

a := 5.0
b := int(a)

Type conversion can only be successful when the definition is correct, such as from a value with a smaller range Type conversion to a type with a larger value range (convert int16 to int32). Precision loss (truncation) occurs when converting from a type with a larger range to a type with a smaller range (converting int32 to int16 or float32 to int).

Only variables of the same underlying type can be converted to each other (such as converting the int16 type to the int32 type). Compilation errors will occur when variables of different underlying types are converted to each other (such as converting the bool type to the int type). ):

package main
import (
        "fmt"
        "math"
)
func main() {
        // 输出各数值范围
        fmt.Println("int8 range:", math.MinInt8, math.MaxInt8)
        fmt.Println("int16 range:", math.MinInt16, math.MaxInt16)
        fmt.Println("int32 range:", math.MinInt32, math.MaxInt32)
        fmt.Println("int64 range:", math.MinInt64, math.MaxInt64)
        // 初始化一个32位整型值
        var a int32 = 1047483647
        // 输出变量的十六进制形式和十进制值
        fmt.Printf("int32: 0x%x %d\n", a, a)
        // 将a变量数值转换为十六进制, 发生数值截断
        b := int16(a)
        // 输出变量的十六进制形式和十进制值
        fmt.Printf("int16: 0x%x %d\n", b, b)
        // 将常量保存为float32类型
        var c float32 = math.Pi
        // 转换为int类型, 浮点发生精度丢失
        fmt.Println(int(c))
}

The code description is as follows:

  • Lines 11 to 14 output the numerical ranges of several common integer types.

  • Line 17, declare the variable a of type int32 and initialize it.

  • Line 19 uses the %x verb of fmt.Printf to output the value in hexadecimal format. This line outputs the 32-bit value of a before conversion.

  • Line 22, convert the value of a to int16 type, that is, convert from 32-bit signed integer type to 16-bit signed integer type. Due to the value range of int16 type The value range is smaller than the int32 type, so the value will be truncated (precision is lost).

  • Line 24 outputs the converted a variable value, which is the value of b, and is also printed in hexadecimal and decimal formats.

  • Line 27, math.Pi is a constant of the math package. It has no type by default. It will be automatically deduced based on the actual type where it is referenced. Here math.Pi is assigned to a variable. c, so the type is float32.

  • Line 29, convert float32 to int type and output.

The code output is as follows:

int8 range: -128 127
int16 range: -32768 32767
int32 range: -2147483648 2147483647
int64 range: -9223372036854775808 9223372036854775807
int32: 0x3e6f54ff 1047483647
int16: 0x54ff 21759
3

According to the output result, the range of 16-bit signed integer is -32768~32767, and the value of variable a, 1047483647, is not in this range Inside. The corresponding hexadecimal value of 1047483647 is 0x3e6f54ff. After converting to int16 type, the length is shortened by half, that is, it is cut in half in hexadecimal and becomes 0x54ff, and the corresponding decimal value is 21759.

When a floating point number is converted to an integer, the decimal part will be removed and only the integer part will be retained.

Type conversion practice

Practical combat 1

package main

import (
   "fmt"
)

// 演示 golang 中基本数据类型的转换
func main() {
   var i int32 = 100
   // 将 i => float
   var n1 float32 = float32(i)
   var n2 int8 = int8(i)
   var n3 int64 = int64(i) // 低精度 => 高精度
   fmt.Printf("i=%v n1=%v n2=%v n3=%v \n", i, n1, n2, n3)
   // 被转换的是变量存储的数据(即值),变量本身的数据类型并没有变化
   fmt.Printf("i type is %T\n", i) // int32
   // 在转换中,比如将 int64  转成 int8 (-128---127) ,编译时不会报错,
   // 只是转换的结果是按溢出处理,和我们希望的结果不一样
   var num1 int64 = 999999
   var num2 int8 = int8(num1)
   fmt.Println("num2=", num2)
}

Test result

i=100 n1=100 n2=100 n3=100
i type is int32
num2= 63

actual combat 2

package main
import (
   "fmt"
   _ "fmt" // 如果我们没有使用到一个包,但是有想去掉,前面加一个 _ 表示忽略
)

func main() {
   // 小练习
   var n1 int32 = 12
   var n2 int64
   var n3 int8
   // n2 = n1 + 20  // int32 ---> int64 错误
   // n3 = n1 + 20  // int32 ---> int8 错误
   n2 = int64(n1) + 20  // 正确
   n3 = int8(n1) + 20  // 正确
   fmt.Println("n2=", n2, "n3=", n3)
}

test result

n2= 32 n3= 32

actual combat 3

package main

import (
   "fmt"
   _ "fmt" // 如果我们没有使用到一个包,但是有想去掉,前面加一个 _ 表示忽略
)

func main() {
   var n1 int32 = 12
   var n3 int8
   var n4 int8
   n4 = int8(n1) + 127 // 编译通过,但是结果 不是 127+12 ,按溢出处理
   n3 = int8(n1) + 128 // 编译不过
   fmt.Println(n4, n3)
}

test result

# command-line-arguments
.\main.go:23:16: constant 128 overflows int8

For more programming-related knowledge, please visit: programming video! !

The above is the detailed content of How to perform data type conversion in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What can golang doNext article:What can golang do