This question already has an answer here:
- golang pointer in range doesn't work 1 answer
For these two struct
type A struct {
Number *int
}
type B struct {
Number int
}
If I want to loop on slice of B and assign the value of B.Number to new A.Number
func main() {
aSlice := []A{}
bSlice := []B{B{1}, B{2}, B{3}}
for _, v := range bSlice {
a := A{}
a.Number = &v.Number
aSlice = append(aSlice, a)
}
}
I will found that all aSlice a.Number is the same value and same pointer.
for _, v := range aSlice {
fmt.Printf("aSlice Value %v Pointer %v
", *v.Number,v.Number)
}
Will print
aSlice Value 3 Pointer 0x10414020
aSlice Value 3 Pointer 0x10414020
aSlice Value 3 Pointer 0x10414020
So does range only update the value of _,v in for loop and doesn't change the pointer ?
Full Code : https://play.golang.org/p/2wopH9HOjwj
</div>