英文:
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]
}
}
英文:
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]
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论