Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - math.MaxInt64 and Type Inference Error

I've been working on metaprogramming involving packages and I've been running into the error constant 9223372036854775807 overflows int whenever math.MaxInt64 and math.MaxUint64 show up.

I've isolated it into two cases:

Valid

var a int64 = math.MaxInt64
b := interface{}(int64(math.MaxInt64))

Not Valid

a := math.MaxInt64
b := interface{}(math.MaxInt64)

https://play.golang.org/p/U1QDmFbV29

It seems like that Go doesn't do correct type inference.

Is this a bug or expected behavior? And if expect, does anyone know why?

like image 696
Tristan Rice Avatar asked Apr 28 '26 08:04

Tristan Rice


1 Answers

math.MaxInt64 is an Untyped Constant. Numeric constants represent values of arbitrary precision and do not overflow. When you assign this to a variable it needs to be converted to a numeric type, and if none is specified, int is used by default.

Since the int type in Go represents the native size for your architecture, this will overflow on systems with 32 bit ints.

like image 87
JimB Avatar answered May 01 '26 06:05

JimB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!