Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Go language type conversion


May 11, 2021 Go


Table of contents


Go language type conversion

Type conversion is used to convert a variable of one data type to another type of variable. The basic format for Go language type conversion is as follows:

type_name(expression)

type_name is a type and expression is an expression.

Instance

In the following example, the integer is converted to a floating-point type and the result is calculated to assign the result to the floating-point variable:

package main

import "fmt"

func main() {
   var sum int = 17
   var count int = 5
   var mean float32
   
   mean = float32(sum)/float32(count)
   fmt.Printf("mean 的值为: %f\n",mean)
}

The output of the above examples is:

mean 的值为: 3.400000


go does not support implicit conversion types

Example:

package main
import "fmt"

func main() {  
    var a int64 = 3
    var b int32
    b = a
    fmt.Printf("b 为 : %d", b)
}

An error will be reported at this point

cannot use a (type int64) as type int32 in assignment
cannot use b (type int32) as type string in argument to fmt.Printf

But if you change b = int32(a) make a mistake:

package main
import "fmt"

func main() {  
    var a int64 = 3
    var b int32
    b = int32(a)
    fmt.Printf("b 为 : %d", b)
}