范围内的golang指针不起作用 [英] golang pointer in range doesn't work

查看:110
本文介绍了范围内的golang指针不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

变量p设置为指向v,而不是slice元素.这段代码将p设置为指向slice元素:

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

游乐场示例

这篇关于范围内的golang指针不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆