【发布时间】:2016-10-10 21:23:37
【问题描述】:
我目前正在学习 Go Lang 教程,确切地说是“数字常量”。示例代码以以下语句开头:
const (
// Create a huge number by shifting a 1 bit left 100 places.
// In other words, the binary number that is 1 followed by 100 zeroes.
Big = 1 << 100
// Shift it right again 99 places, so we end up with 1<<1, or 2.
Small = Big >> 99
)
常量Big 显然很大,我正在尝试打印它及其类型,如下所示:
fmt.Printf("%T", Big)
fmt.Println(Big)
但是,两行都出现以下错误:
# command-line-arguments ./compile26.go:19: 常量 1267650600228229401496703205376 溢出 int
我会尝试将 Big 转换为其他类型,例如 uint64,它会因相同的错误而溢出,或者只是将其转换为字符串,但在尝试 Big.String() 时出现以下错误:
Big.String 未定义(int 类型没有字段或方法 String)
它的类型似乎是int,但我不能打印它或将它转换为任何东西,它会溢出所有方法。我该如何处理这个数字/对象以及如何打印它?
【问题讨论】:
-
Go 中的 const 是 not 正常变量,恰好是 const,它们是不同的。 const 的概念仅在编译期间存在,const 具有任意(几乎)精度,并且大小和算术是可能的。当 使用 一个 const 时,它会被转换为“正确的”类型。这种转换可能会失败,就像您的程序格式错误一样。没有(直接、简单)的方式来打印
Big。 -
@Volker @arik 如果您将 const 显式键入为 float64 或 complex128,您似乎可以打印它。那么,
Big的值作为 float64 是否不同于隐式类型Big的值,后者在使用时会在运行时转换为正确的类型?const Big float64 = 1 << 100fmt.Printf("Type of Big is: %T, Value of Big is %v", Big, Big)这打印“Big 的类型是:float64,Big 的值是 1.2676506002282294e+30”
标签: go biginteger integer-overflow