Go gotcha: Why can't I print large numbers? (constant overflows int)

Why doesn’t this code compile?

const n = 9876543210 * 9876543210
fmt.Println(n)
../main.go:2:13: constant 97546105778997104100 overflows int
Answer

The untyped constant n must be converted to a type before it can be assigned to the interface{} parameter in the call to

fmt.Println(a ...interface{})

When the type can’t be inferred from the context, an untyped constant is converted to a bool, int, float64, complex128, string or rune depending of the format of the constant.

In this case the constant is an integer, but n is larger than the maximum value of an int.

However, n can be represented as a float64:

const n = 9876543210 * 9876543210
fmt.Println(float64(n))
9.75461057789971e+19

For exact representation of big numbers, the math/big package implements arbitrary-precision arithmetic. It supports signed integers, rational numbers and floating-point numbers.

Comments