go - golang 数学/大库中的奇怪语法

标签 go syntax binary-operators language-implementation

<分区>

我正在使用 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 上的例子.

关于go - golang 数学/大库中的奇怪语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47572340/

相关文章:

phpStorm 在一些 .ctp 文件中显示 php 语法

python - 为什么这样做呢?

algorithm - 切换除最高设置位之后的所有位

go - docker 错误 : Volume specifies nonexistent driver inmemory

go - Aerospike 测试环境

Go 为外部包导出常量报告 "undefined"

java - java 8中两个列表的合并函数

Golang,类型为字符串的变量

c++ - 在C++中错误地像array [1-00]那样声明了数组,但是代码仍然有效,输出不正确?

c++ - 了解重载的 operator[] 示例