为什么在Go语言中,big.NewInt(0).Bytes()返回[]而不是[0]?

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

Why big.NewInt(0).Bytes() returns [] instead of [0] in Go?

问题

我发现奇怪的是,运行big.NewInt(0).Bytes()返回的是[]而不是[0]。它真的应该这样工作吗?

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

英文:

I find it weird that running big.NewInt(0).Bytes() returns [] instead of [0]. Is it really supposed to work that way?

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

答案1

得分: 5

big.Int是一个结构体。在可能的情况下,使用零值是符合惯例的。big.Int也不例外:Int类型的零值表示为0

这是一个实现细节,但是Int的数据存储在一个切片中。切片的零值是nil,也就是没有元素。

所以这非常方便,也非常高效。0可能是最常见的值,而且可能存在一些情况下,初始的big.Int不会被改变,因此不会分配内部表示的切片。

参考链接:https://stackoverflow.com/questions/64257065/is-there-another-way-of-testing-if-a-big-int-is-0/64257532#64257532

英文:

big.Int is a struct. It's idiomatic to make the zero value useful whenever possible. big.Int is no exception: The zero value for an Int represents the value 0.

It's an implementation detail, but the data of the Int is stored in a slice. The zero value for slices is nil, that is: no elements.

So this is very convenient, and very efficient. 0 is probably the most frequent value, and there may be cases where an initial big.Int won't get changed, and so no slice for the internal representation will be allocated.

See related: https://stackoverflow.com/questions/64257065/is-there-another-way-of-testing-if-a-big-int-is-0/64257532#64257532

答案2

得分: 2

文档中可以得知:
> Bytes函数将x的绝对值作为大端字节切片返回。

该包的API并未定义切片的长度。在这种情况下,它使用了最少的字节数来表示整个数字。

这种情况更有可能是一个实现细节:big.Int在一个切片中保存数字的字节。在Go中,空切片(切片的零值)的长度为0。当创建一个big.Int值时,我们期望它的值也为0。因此,如果一个空切片在内部对应于数值0,就不需要执行额外的检查或填充,这样可以简化实现。

英文:

From the documentation:
> Bytes returns the absolute value of x as a big-endian byte slice.

The package API doesn't define how many bytes long the slice will be. In this case, it's using the smallest number of bytes needed to convey the whole number.

The more likely reason why this happens is an implementation detail: The big.Int maintains the bytes of the number in a slice. nil slices in Go (the zero value of a slice) have length 0. When a big.Int value is initially created, we'd expect it to also have a value of 0. Therefore, it simplifies the implementation if an empty slice internally corresponds to a numerical value of 0, without needing to perform extra checks or padding.

huangapple
  • 本文由 发表于 2021年6月10日 01:07:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/67908738.html
匿名

发表评论

匿名网友

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

确定