如何在Go中使用big包链接操作?

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

How to chain operations in go using big package?

问题

例如,如果我想执行 r = a * (b - c)。我会这样做:

var r, a, b, c, t big.Int

t.Sub(&b, &c)
r.Mul(&a, &t)

在包文档中,它说操作返回结果以允许链接。但由于使用的变量不是用作操作符参数,而只是用于存储结果,那么我如何链接操作呢?换句话说,我如何在只有一行代码的情况下编写我的示例,而不使用临时变量 t

英文:

For example, if I want to perform r = a * (b - c). I would do:

var r, a, b, c, t big.Int

t.Sub(&b, &c)
r.Mul(&a, &t)

In package documentation, it says that operations return result to allow chaining. But since the used variable isn't used as operator argument, but only to store result, how can I chain operations? In other words, how could I write my exemple using only one line of code, without temporary variable t?

答案1

得分: 4

例如,在Go 1上,

package main

import (
	"fmt"
	"math/big"
)

func main() {
	var r, a, b, c big.Int
	a = *big.NewInt(7)
	b = *big.NewInt(42)
	c = *big.NewInt(24)

	// r = a * (b - c)
	r.Mul(&a, r.Sub(&b, &c))

	fmt.Println(r.String())
}

输出:

126
英文:

For example, on Go 1,

package main

import (
	"fmt"
	"math/big"
)

func main() {
	var r, a, b, c big.Int
	a = *big.NewInt(7)
	b = *big.NewInt(42)
	c = *big.NewInt(24)

	// r = a * (b - c)
	r.Mul(&a, r.Sub(&b, &c))

	fmt.Println(r.String())
}

Output:

126

huangapple
  • 本文由 发表于 2012年3月3日 23:20:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/9547212.html
匿名

发表评论

匿名网友

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

确定