[Golang] The basic syntax of the data type conversion

In some programming languages ​​there exists implicit type conversion, for example, JavaScript.

var a = 10 
var b = "a"
console.log(a + b) // 10a

The above js code implicit conversion occurs during execution, the number of variable type automatic conversion to a string, and the string type b after performing the addition, string concatenation occurs.

But this implicit type conversion, which is the go language does not exist.

Where necessary go, allowing a value into a value type to another type. But all the casts must display the statement came out.

Example:

valTypeB = TypeB(valTypeA)

Type B value = (value of A type) Type B of

For example the following example:

// 定义一个变量
var s1 string = "hello,world"
var a = []byte(s1) // 将字符串转换为数组
var n1 float64 = 1.0
var b int = int(n1) // 将float64转换为整型

Type conversion only under the definition of a successful conversion is correct, for example, from a smaller range to a larger type of a range of types (int16 is converted to the int32). When a type conversion from a larger to a smaller range in the range of type (which is converted to the int32 int16 or float32 convert int), where loss of precision (cut) may occur.

Only conversion may be performed between the same type of underlying variable (e.g., converted into an int32 int16 type), a compilation error cause different types of underlying variable conversion (e.g., converted to an int bool):

// int 32 最大值:2147483647
var n1 int64 = 2147483648
var n2 int32 = int32(n1)
fmt.Println(n2) // -2147483648
// 底层不同的数据进行转换
var b1 bool = true
var n1 int = int(b1)
fmt.Println(n1) // cannot convert b1 (type bool) to type int

Guess you like

Origin www.cnblogs.com/liujunhang/p/12534420.html