Go – math.MaxInt64 and Type Inference Error

huangapple go评论83阅读模式
英文:

Go - math.MaxInt64 and Type Inference Error

问题

我一直在进行涉及包的元编程工作,但每当出现math.MaxInt64math.MaxUint64时,我都会遇到错误constant 9223372036854775807 overflows int

我将其分为两种情况:

有效的:

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

无效的:

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

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

看起来Go语言没有正确的类型推断。

这是一个bug还是预期行为?如果是预期行为,有人知道原因吗?

英文:

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?

答案1

得分: 7

math.MaxInt64 是一个无类型常量。数值常量表示任意精度的值,不会溢出。当你将其赋值给一个变量时,需要将其转换为数值类型,如果没有指定类型,默认使用 int

由于 Go 中的 int 类型表示与你的架构相匹配的本机大小,因此在具有 32 位 int 的系统上会发生溢出。

英文:

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.

huangapple
  • 本文由 发表于 2015年3月28日 04:47:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/29309922.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定