~/Type Conversions in Golang Explained

Mar 15, 2021


Go or Golang requires explicit type conversions when changing a variable from one type to another. Go does not allow automatic or implicit type conversions, so you must use the syntax T(v) where T is the target type and v is the value.

Basic Example:

1
2
3
var i int = 42
var f float64 = float64(i)
var u uint = uint(f)

You cannot directly convert between unrelated types like string and int. To convert a string to int, use strconv.Atoi:

1
2
3
4
import "strconv"

s := "123"
i, err := strconv.Atoi(s)

To convert an int to string:

1
2
3
4
import "strconv"

i := 123
s := strconv.Itoa(i)

Byte slice and string conversions are common. Convert string to byte slice:

1
2
s := "hello"
b := []byte(s)

And from byte slice to string:

1
2
b := []byte{104, 101, 108, 108, 111}
s := string(b)

If types are not explicitly convertible, Go will show a compile error. Always use the correct conversion or helper functions. For more, visit the Go spec on conversions.

Tags: [golang] [types]