golang pointer in range doesn't work

僤鯓⒐⒋嵵緔 提交于 2019-12-31 07:43:05

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/35306669/golang-pointer-in-range-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!