golang pointer in range doesn't work

huangapple go评论90阅读模式
英文:

golang pointer in range doesn't work

问题

为什么结果是 A:&{[{[{1}]}]}A:&{[{[{2}]}]}A:&{[{[{2}]}]} 而不是 A:&{[{[{1}]}]}A:&{[{[{2}]}]}A:&{[{[{3}]}]}?我们不能在 range 循环中使用指针吗?这是代码,我在 range 循环中设置了一个指针,但它失败了。

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)
}
英文:

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

得分: 0

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

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

playground示例

英文:

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

huangapple
  • 本文由 发表于 2016年2月10日 12:10:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/35306669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定