Type conversions

The expression T(v) converts the value v to the type T.

Some numeric conversions:

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

Or, put more simply:

  1. i := 42
  2. f := float64(i)
  3. u := uint(f)

Unlike in C, in Go assignment between items of different type requires an explicit conversion. Try removing the float64 or uint conversions in the example and see what happens.

type-conversions.go

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. var x, y int = 3, 4
  8. var f float64 = math.Sqrt(float64(x*x + y*y))
  9. var z uint = uint(f)
  10. fmt.Println(x, y, z)
  11. }