Notessh2a

Type Casting

Type casting is the explicit conversion of a value from one compatible type to another.

newValue := targetType(value)

Go does not allow implicit conversions. This prevents hidden bugs and keeps behavior predictable.

a := 5.6 // float64
b := 10 // int

c := a + b // <-- compiler: invalid operation: a + b (mismatched types float64 and int)

c := a + float64(b) // 15.6 (float64)
  • Casting from float to integer removes (cuts off) the decimal part:

    a := 5.6 // float64
    
    b := int16(a) // 5 (int16)
    
    c := float64(b) // 5 (float64)
  • Casting between integer sizes must also be explicit:

    var a int64 = 100
    var b int32 = 50
    
    c := int32(a) + b // 150 (int32)
  • Casting from string to []byte or []rune changes the representation:

    a := "1aé"
    
    b := []byte(a) // [49 97 195 169] (UTF-8 bytes)
    c := []rune(a) // [49 97 233] (Unicode code points)
  • Some types cannot be cast directly if they are not compatible:

    a := "123"
    
    b := int(a) // <-- compiler: cannot convert a (variable of type string) to type int