Numbers and conversions

Integers do not turn into each other silently, and overflow is not caught by a panic.

Numeric types in Go do not mix. int and int64 are different types, even if on your machine both take 8 bytes. You cannot add them without a conversion:

var a int = 1
var b int64 = 2
sum := int64(a) + b

The conversion int64(a) produces a value of the new type. It is not "a cast that sometimes fails", and it is not a range check. If the value does not fit in the target type, the extra bits are quietly discarded. There will be no panic. A narrowing conversion is therefore a place where Middle code either checks the bounds in advance or chooses a wider type.

int is the machine word for indexes and lengths. For money, protocol identifiers, and anything that will outlive a file or the network, take an explicit size: int64, uint32. byte is a synonym of uint8. rune is a synonym of int32 and means a Unicode code point, not "a character on the screen" and not a byte.

Integer division discards the fractional part toward zero: -3 / 2 equals -1. The remainder % takes the sign of the dividend. For positive indexes this usually does not matter. For offsets, it does.

Constants are more flexible than variables. The constant 1 has no type until the context demands one, so it can be passed both as int and as float64. Once the value has landed in a variable, the flexibility is gone.

const one = 1
var i int = one
var f float64 = one

A practical conclusion

Do not write float64 where an exact integer is required: money in a float is a classic mistake. Store cents in int64, or use a decimal type if the domain requires it. For ordinary counters, int is enough.

Practice

  1. Different integers

    There is var a int and var b int64. Which of these compiles?

    • fmt.Println(a + b)
    • fmt.Println(int64(a) + b)
    • fmt.Println(a + int(b)) only if a and b are constants; variables can never be written that way
    • fmt.Println((a + b).(int64))
  2. A sum

    Write a function Sum(a, b int) int that returns the sum of the arguments. Negative numbers must add in the ordinary way too.

  3. Integer division

    What is the expression 7 / 2 equal to for the type int? Write one number.