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)
}