go - 如果标准 golang big.Int 函数接受两个参数并返回一个值,为什么它要使用接收器?

标签 go

功能:

// Mod sets z to the modulus x%y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs.
// Mod implements Euclidean modulus (unlike Go); see DivMod for more details.
func (z *Int) Mod(x, y *Int) *Int {

如果我想在条件下使用函数,我需要创建一个临时变量以避免被覆盖:

var tmp big.Int
for tmp.Mod(x, y).Cmp(z) == 0 {
  1. 这样做有什么实际好处吗?
  2. 我可以在不使用临时变量的情况下重写代码吗?

最佳答案

通常,接收器用于结果,因此您可以选择重用现有的 big.Int 实例。如果您不想重用现有的结果,您可以为结果创建一个新的结果并调用该结果的方法。

math/big的包文档中提到了这一点:

By always passing in a result value via the receiver, memory use can be much better controlled. Instead of having to allocate new memory for each result, an operation can reuse the space allocated for the result value, and overwrite that value with the new result in the process.

结果也会返回,以便您可以链接调用。包文档中也提到了这一点:

For instance, the arguments for (*Int).Add are named x and y, and because the receiver specifies the result destination, it is called z:

func (z *Int) Add(x, y *Int) *Int

Methods of this form typically return the incoming receiver as well, to enable simple call chaining.

所以你可以这样做:

one := big.NewInt(1)
two := big.NewInt(2)
three := big.NewInt(3)

sum := new(big.Int)
sum.Add(sum, one).Add(sum, two).Add(sum, three)
fmt.Println(sum)

它将输出(在 Go Playground 上尝试):

6

如果您不想重复使用现有值作为操作结果,您可以分配一个新值,如下所示:

one := big.NewInt(1)
two := big.NewInt(2)

fmt.Println(new(big.Int).Add(one, two))

打印 3 (在 Go Playground 上试试)。

关于go - 如果标准 golang big.Int 函数接受两个参数并返回一个值,为什么它要使用接收器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69850718/

相关文章:

gomail noauth 示例崩溃

multithreading - go lang 中不正确的同步

go - 如何删除多级 map

Golang Mgo 节奏

go - 在golang中全局设置时区

for-loop - Go中for循环内的错误处理可能会导致下一次迭代

go - 使用http Mux请求正文验证

go - 记录到 stderr 和 stdout golang Google Cloud Platform

function - 尝试取消引用一个接口(interface),该接口(interface)是指向后端结构对象的指针,因此我可以按值传递给函数

go - 在一系列系统调用中是否有更简洁的错误处理方式?