There is no implicit conversion in Go, and the type conversion needs to be explicitly declared.
The expression T(v)
converts the value v
to the type T
.
Int, uint, and float can be converted to each other using T(v) expressions.
var i int = 21
var i64 int64 = int64(i)
var f float64 = float64(i)
var u uint = uint(f)
Byte, []byte, and string can be converted mutually using T(v) expressions.
var b []byte = []byte("golang")
var s string = string(b)
The following is a complete code example.
package main
import "fmt"
func main() {
var i int = 21
fmt.Printf("int64(i) type is %T\n", int64(i))
fmt.Printf("float64(i) type is %T\n", float64(i))
fmt.Printf("uint(float64(i)) type is %T\n", uint(float64(i)))
var b []byte = []byte("golang")
fmt.Printf("string(b) type is %T\n", string(b))
}
Below is the program output:
int64(i) type is int64
float64(i) type is float64
uint(float64(i)) type is uint
string(b) type is string