【问题标题】:golang pointer in range doesn't work范围内的golang指针不起作用
【发布时间】:2016-02-10 04:10:38
【问题描述】:

为什么结果是A:&{[{[{1}]}]}A:&{[{[{2}]}]}A:&{[{[{2}]}]}

不是:A:&{[{[{1}]}]}A:&{[{[{2}]}]}A:&{[{[{3}]}]}

我们不能在范围内使用指针? 这是代码,我设置了一个指针,指向范围循环,但它失败了。

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

【问题讨论】:

    标签: pointers go range


    【解决方案1】:

    变量p 设置为指向v,而不是切片元素。此代码将p 设置为指向切片元素:

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

    playground example

    【讨论】:

      猜你喜欢
      • 2019-05-09
      • 2011-07-22
      • 2021-09-17
      • 2016-11-06
      • 2014-05-31
      • 2011-02-26
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      相关资源
      最近更新 更多