Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value generated from range have same pointer value [duplicate]

Tags:

go

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\n", *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

like image 826
Ali Dabour Avatar asked Oct 20 '25 02:10

Ali Dabour


1 Answers

It occurred because variable v is created at the beginning of the loop and doesn't change. So, every element in aSlice has a pointer to the same variable. You should write this:

for _, v := range bSlice {
    a := A{}
    v := v
    a.Number = &v.Number
    aSlice = append(aSlice, a)
}

Here you create at every iteration new variable with its own pointer.

like image 51
PhyZiK Avatar answered Oct 22 '25 01:10

PhyZiK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!