英文:
Go - math.MaxInt64 and Type Inference Error
问题
我一直在进行涉及包的元编程工作,但每当出现math.MaxInt64
和math.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 int
s.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论