golang pointer in range doesn't work

lucky liang

Why the result is A:&{[{[{1}]}]}A:&{[{[{2}]}]}A:&{[{[{2}]}]}

not: A:&{[{[{1}]}]}A:&{[{[{2}]}]}A:&{[{[{3}]}]}

we can't use pointer in range? here is the code, I set a pointer, pointed in the range loop, but it fails.

package main

import(
    "fmt"
)

type A struct{
    Barry []B
}
func (this *A)init(){
    b:=&B{}
    b.init()
    this.Barry=[]B{*b}
    return 
}
type B struct{
    Carry []C
}
func (this *B)init(){
    c:=&C{}
    c.init()
    this.Carry=[]C{*c}
    return 
}
type C struct{
    state string
}
func (this *C)init(){
    this.state="1"
    return 
}
func main(){
    a:=&A{}
    a.init()
    fmt.Printf("A:%v\n",a)
    p:=&a.Barry[0].Carry[0]
    p.state="2"
    fmt.Printf("A:%v\n",a)


    for _,v:=range a.Barry[0].Carry{
        if v.state=="2"{
            p=&v
        }
    }
    p.state="3"
    fmt.Printf("A:%v\n",a)
}
Muffin Top

The variable p is set to point at v, not to the slice element. This code sets p to point at the slice element:

for i, v := range a.Barry[0].Carry {
    if v.state == "2" {
        p = &a.Barry[0].Carry[i]
    }
}

playground example

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related