Go 如何对常量进行算术运算?

分享于2022年07月17日 constants go 问答
【问题标题】:Go 如何对常量进行算术运算?(How does Go perform arithmetic on constants?)
【发布时间】:2022-01-28 13:00:44
【问题描述】:

我一直在阅读这个 post on constants in Go ,并试图了解它们是如何在内存中存储和使用的。您可以在 Go 中对非常大的常量执行操作,只要结果适合内存,您就可以将该结果强制转换为类型。例如,此代码打印 10 ,正如您所期望的那样:

const Huge = 1e1000
fmt.Println(Huge / 1e999)

这在后台是如何工作的?在某些时候,Go 必须将 1e1000 1e999 存储在内存中,以便对它们执行操作。那么常量是如何存储的,Go 又是如何对它们进行算术运算的呢?


【解决方案1】:

简短的总结 (TL;DR) 在答案的末尾。

无类型的任意精度常量不存在于运行时,常量只存在于编译时(编译期间)。话虽如此,Go 不必在运行时以任意精度表示常量,仅在编译应用程序时。

为什么?因为常量不会被编译到可执行的二进制文件中。他们不必是。举个例子吧:

const Huge = 1e1000
fmt.Println(Huge / 1e999)

源代码 中有一个常量 Huge (并且将在包对象中),但它不会出现在您的可执行文件中。相反,对 fmt.Println() 的函数调用将被记录为传递给它的值,其类型将为 float64 。所以在可执行文件中只有一个 float64 值是 10.0 将被记录。可执行文件中没有任何数字为 1e1000 的迹象。

float64 类型派生自 无类型 常量 Huge 默认 类型。 1e1000 floating-point literal 。要验证它:

const Huge = 1e1000
x := Huge / 1e999
fmt.Printf("%T", x) // Prints float64

回到任意精度:

Spec: Constants:

数值常量表示任意精度的精确值,不会溢出。

所以常量代表任意精度的精确值。正如我们所看到的,在 运行时 不需要以任意精度表示常量,但是编译器仍然需要在 编译时 做一些事情。它 确实

显然无法处理“无限”精度。但是没有必要,因为源代码本身不是“无限的”(源代码的大小是有限的)。尽管如此, 允许 真正的任意精度是不切实际的。因此,规范为编译器提供了一些自由:

实现限制:尽管数字常量在语言中具有任意精度,但编译器可以使用具有有限精度的内部表示来实现它们。也就是说,每个实现都必须:

  • 用至少 256 位表示整数常量。
  • 用至少 256 位尾数和至少 32 位带符号指数表示浮点常量,包括复数常量的部分。
  • 如果无法精确表示整数常量,则会报错。
  • 如果由于溢出而无法表示浮点或复数常量,则给出错误。
  • 如果由于精度限制而无法表示浮点或复数常数,则舍入到最接近的可表示常数。 这些要求既适用于文字常量,也适用于评估 constant expressions 的结果。

但是,还请注意,当上述所有内容时,标准包为您提供了仍然以“任意”精度表示和使用值(常量)的方法,请参阅包 go/constant 。您可以查看它的源代码以了解它是如何实现的。

go/constant/value.go 中实现。表示此类值的类型:

// A Value represents the value of a Go constant.
type Value interface {
    // Kind returns the value kind.
    Kind() Kind

    // String returns a short, human-readable form of the value.
    // For numeric values, the result may be an approximation;
    // for String values the result may be a shortened string.
    // Use ExactString for a string representing a value exactly.
    String() string

    // ExactString returns an exact, printable form of the value.
    ExactString() string

    // Prevent external implementations.
    implementsValue()
}

type (
    unknownVal struct{}
    boolVal    bool
    stringVal  string
    int64Val   int64                    // Int values representable as an int64
    intVal     struct{ val *big.Int }   // Int values not representable as an int64
    ratVal     struct{ val *big.Rat }   // Float values representable as a fraction
    floatVal   struct{ val *big.Float } // Float values not representable as a fraction
    complexVal struct{ re, im Value }
)

如您所见, math/big 包用于表示无类型的任意精度值。 big.Int 是例如(来自 math/big/int.go ):

// An Int represents a signed multi-precision integer.
// The zero value for an Int represents the value 0.
type Int struct {
    neg bool // sign
    abs nat  // absolute value of the integer
}

nat 在哪里(来自 math/big/nat.go ):

// An unsigned integer x of the form
//
//   x = x[n-1]*_B^(n-1) + x[n-2]*_B^(n-2) + ... + x[1]*_B + x[0]
//
// with 0 <= x[i] < _B and 0 <= i < n is stored in a slice of length n,
// with the digits x[i] as the slice elements.
//
// A number is normalized if the slice contains no leading 0 digits.
// During arithmetic operations, denormalized values may occur but are
// always normalized before returning the final result. The normalized
// representation of 0 is the empty or nil slice (length = 0).
//
type nat []Word

最后 Word 是(来自 math/big/arith.go

// A Word represents a single digit of a multi-precision unsigned integer.
type Word uintptr

总结

在运行时: 预定义 类型提供有限的精度,但您可以使用某些包“模仿”任意精度,例如 math/big go/constant 。在编译时:常量看似提供任意精度,但实际上编译器可能达不到这一点(不一定);但是该规范仍然为所有编译器必须支持的常量提供了最小的精度,例如整数常量必须至少用 256 位表示,即 32 字节(与 int64 相比,“仅”8 字节)。

创建可执行二进制文件时,必须转换常量表达式(具有任意精度)的结果并用有限精度类型的值表示——这可能是不可能的,因此可能会导致编译时错误。请注意,只有 结果 ——不是中间操作数——必须转换为有限精度,常数运算以任意精度执行。

规范没有定义如何实现这种任意或增强的精度, math/big 例如将数字的“数字”存储在切片中(其中数字不是以 10 为基数表示的数字,而是“数字”是一个 uintptr ,类似于 32 位架构上的基本 4294967295 表示,在 64 位架构上甚至更大)。

  • 非常彻底和乐于助人!这是我基于此的理解:在运行时没有什么是任意精度的。在编译时,编译器的精确精度可能会有所不同,但本质上是对存储为基本类型切片的特殊任意精度类型执行操作(至少对于整数,我必须检查其他类型)。然后将它们强制转换为标准 Go 类型以供运行时使用。这准确吗?
  • @LizSander 编辑了答案,在末尾添加了 Summary 部分(这是您评论的答案)。