我正在使用 golang 中的 math/big
库对位串执行操作。一切正常,但我很困惑为什么对于这个库的大部分函数,语法是:
var num1 big.Int
var num2 big.Int
var result big.Int
// Set num1 and num2
result.And(&num1,&num2)
代替:
var num1 big.Int
var num2 big.Int
// Set num1 and num2
result = num1.And(num2)
因为 And
等函数也返回运算结果 ( https://golang.org/src/math/big/int.go?s=18912:18945#L798 )。
为什么您认为这是选择的实现方式?
这可能是因为性能或众所周知的不良垃圾收集?
这只是单纯的好奇心,提前致谢!
不知道有什么奇怪的,这和非大操作的运作方式是一致的。例如。在 int
操作数上使用按位 AND 不会更改操作数:
a, b := 3, 15
c := a & b
fmt.Println(c) // Prints 3
x, y := big.NewInt(3), big.NewInt(15)
z := new(big.Int).And(x, y)
fmt.Println(z) // Prints 3
这也意味着如果你准备了一个变量,你可以将它用作“目标”,来存储结果。就像您可以使用现有的 int
变量来存储上述 a & b
表达式的结果:
c = a & b
z.And(x, y)
这意味着您不需要重新分配新的 big.Int
值来获得结果(性能影响)。
而且这些方法通常返回相同的指针,因此您可以链接特定的操作。
Methods of this form typically return the incoming receiver as well, to enable simple call chaining.
所以你也可以这样做:
fmt.Println(z.And(x, y).BitLen()) // Prints 2
试试 Go Playground 上的例子.