I’m trying to understand the design decisions behind the big int api.
For example to add two big ints you have to:
a := big.NewInt(10)
b := big.NewInt(20)
c := big.NewInt(0)
d := c.Add(a,b)
where d is the same as c at the end. The initial zero does not matter a bit.
Why not just:
a := big.NewInt(10)
b := big.NewInt(20)
c := big.Add(a,b)
Or better yet:
a := big.NewInt(10)
b := big.NewInt(20)
c := a.Add(b)
Is there any reason they chose to do it this way? I find it little confusing and have to look it up whenever I use it.
Addis a method changing the receiver.So just do
or
The fact that Add returns the receiver is useful for function chaining but you don’t need to use the returned value.
Now suppose a moment that we wouldn’t have a bigInt as receiver (
c := big.Add(a,b)) or that the receiver wouldn’t be modified (c := a.Add(b)). In both cases a big Int would have to be allocated just for the operation and returned (as a pointer). This would be wasteful in case you yet have a big Int allocated and ready. The integer that is computed isn’t just a simple one or two words struct, it can be big. So it’s better to allow the use of a predefined var, especially as you often would use your big integer in the middle of a computation loop.