The following Go program produces 1,2,3,4 in followed by 5,5,5,5. I was expecting 1,2,3,4 in both cases. What am I doing wrong?
package main
import (
"fmt"
"math/big"
)
func primesLessThan(n *big.Int) (primes []big.Int) {
var one big.Int
one.SetInt64(1)
var i big.Int
i.SetInt64(1)
for i.Cmp(n) < 0 {
fmt.Println(i.String())
primes = append(primes, i)
i.Add(&i, &one)
}
return
}
func main() {
primes := primesLessThan(big.NewInt(5))
for _, p := range primes {
fmt.Println(p.String())
}
}
Update: the following code snippet illustrates the unexpected side effects of the shallow copy described in the responses. The output of the following snippet is 3, 3
one := big.NewInt(1)
two := big.NewInt(2)
one = two // Shallow copy. Question: how do I do a deep copy?
one.SetInt64(3) // Side-effect: also changes two
fmt.Println(one.String())
fmt.Println(two.String())