英文:
Why is the .Bytes() value of a 0 big.Int an empty slice?
问题
为什么在零值 big.Int 上调用 .Bytes() 方法会返回长度为0的切片?
	// uint64
	var x uint64
	xb := make([]byte, 8)
	binary.BigEndian.PutUint64(xb, x)
	// [0 0 0 0 0 0 0 0]
	fmt.Println(xb)
	// uint8
	var y uint8
	yb := []byte{byte(y)}
	// [0]
	fmt.Println(yb)
	// big.Int
	z := big.Int{}
	zb := z.Bytes()
	// []				为什么这是一个空切片而不是 [0]?
	fmt.Println(zb)
英文:
Why does calling .Bytes() on a zero value big.Int return a slice of length 0?
	// uint64
	var x uint64
	xb := make([]byte, 8)
	binary.BigEndian.PutUint64(xb, x)
	// [0 0 0 0 0 0 0 0]
	fmt.Println(xb)
	// uint8
	var y uint8
	yb := []byte{byte(y)}
	// [0]
	fmt.Println(yb)
	// big.Int
	z := big.Int{}
	zb := z.Bytes()
	// []				Why is this an empty slice and not [0]
	fmt.Println(zb)
答案1
得分: 2
big.Int 在一个切片中存储它所表示的数的绝对值。big.Int 的文档中指出:“Int 的零值表示值 0”。因此,在零值(表示 0)中,该切片将为空(切片的零值是 nil,而 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 stores the absolute value of the number it represents in a slice. big.Int documents that "the zero value for an Int represents the value 0". So in the zero value (which represents 0) the slice will be empty (zero value for slices is nil and the length of a nil slice is 0).
The reasoning is simple: in cases where you don't use a big.Int value, it won't require allocation for the slice. Zero is the most special and probably the most frequent value, using this simple trick is a "no-brainer" optimization.
See related question: https://stackoverflow.com/questions/64257065/is-there-another-way-of-testing-if-a-big-int-is-0/64257532#64257532
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论