Does not work constant 214748364899 without type declaration on 32bit platforms?

On the site golang.org I tried run the following:

package main

import "fmt"

func main() {
	fmt.Println(214748364899)
}

and got the error:

tmp/sandbox212354298/main.go:7: constant 214748364899 overflows int

But on my 64bit ubuntu I don’t have this error.
Does it mean that all integer constants bigger than 2147483647 work without type declaration on 64bit platforms only?

1 Like

What you are seeing is the interaction between two rules in the go specification.

This first is literal constants are untyped until they are used, at which point they are coerced into a type. The type they are coerced into is the type of the variable on the left hand side of the assignment, the type of another value on the right hand side of the assignment, or the type of a parameter for a method or function.

So, now we know that that literal constants is going to be coerced into an integer type (as it is a literal integer), but which type will it be? There is no assignment, so we can rule out the first three options, leaving us with the rule “coerced into the type of the parameter”.

However, fmt.Println takes pamemeters of interface{}, which is to say, any type will work, so this doesn’t provide any assistance. In these cases the spec says that the untyped integer constant will be coerced into the int type.

So, now we know that 214748364899 is being coerced into an int. As you’ve discovered the size of the 214748364899 is more than will fit in a 32 bit integer, which means play.golang.org is a 32 bit system (or pretends to be). When you run your program on a 64 bit system, the size of int is now larger, 64bits, not 32bits, so your program works.

One solution is to give the compiler a hint that you want to express 214748364899 as an int64 with this syntax.

fmt.Println(int64(214748364899))
4 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.