In the code snippet below, I want to make a very simple calculation d = a + b + c; a, b, c = b, c, d
. It iterates several times.
In the first try, I make an anonymous variable big.NewInt(0).Add(a, b)
to get the result of a + b
, then add it and c
to get the final result of a + b + c
. But from the second iteration, d.Add(big.NewInt(0).Add(a, b), c)
changed the value of c
, then b
, then a
, and of course, the final result is wrong.
However, the second try's method gave me the right answer. Can anyone tell me why, please?
package main
import (
"fmt"
"math/big"
)
func main() {
// first try
a := big.NewInt(1)
b := big.NewInt(2)
c := big.NewInt(3)
d := big.NewInt(0)
for i := 0; i < 5; i++ {
// d = a + b + c
d.Add(big.NewInt(0).Add(a, b), c)
fmt.Println(a, b, c, d)
// a <- b, b <- c, c <- d
a, b, c = b, c, d
fmt.Println(a, b, c, d)
}
fmt.Println(d)
// second try
a = big.NewInt(1)
b = big.NewInt(2)
c = big.NewInt(3)
d = big.NewInt(0)
for i := 0; i < 5; i++ {
// d = a + b + c
d = big.NewInt(0).Add(big.NewInt(0).Add(a, b), c)
fmt.Println(a, b, c, d)
// a <- b, b <- c, c <- d
a, b, c = b, c, d
fmt.Println(a, b, c, d)
}
fmt.Println(d)
}
math/big.NewInt returns a pointer to an Int
, so after your first iteration, both c
and d
point to the same object. This means, in your second iteration, when you add something to d
, the same change will be reflected in c
. Then you copy c
to b
so b
will also point to the same object, and on the next iteration b
to a
, so after your third iteration, all 4 variables point to the same Int
.
Your second loop works because you create a new Int
for d
each time, so every time you shift the pointers, a new Int
(the one which was created for d
) gets moved to c
, then to b
, then to a
.