golang pointer in range doesn't work

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

golang pointer in range doesn't work

问题

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

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type A struct {
  6. Barry []B
  7. }
  8. func (this *A) init() {
  9. b := &B{}
  10. b.init()
  11. this.Barry = []B{*b}
  12. return
  13. }
  14. type B struct {
  15. Carry []C
  16. }
  17. func (this *B) init() {
  18. c := &C{}
  19. c.init()
  20. this.Carry = []C{*c}
  21. return
  22. }
  23. type C struct {
  24. state string
  25. }
  26. func (this *C) init() {
  27. this.state = "1"
  28. return
  29. }
  30. func main() {
  31. a := &A{}
  32. a.init()
  33. fmt.Printf("A:%v\n", a)
  34. p := &a.Barry[0].Carry[0]
  35. p.state = "2"
  36. fmt.Printf("A:%v\n", a)
  37. for _, v := range a.Barry[0].Carry {
  38. if v.state == "2" {
  39. p = &v
  40. }
  41. }
  42. p.state = "3"
  43. fmt.Printf("A:%v\n", a)
  44. }
英文:

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.

  1. package main
  2. import(
  3. "fmt"
  4. )
  5. type A struct{
  6. Barry []B
  7. }
  8. func (this *A)init(){
  9. b:=&B{}
  10. b.init()
  11. this.Barry=[]B{*b}
  12. return
  13. }
  14. type B struct{
  15. Carry []C
  16. }
  17. func (this *B)init(){
  18. c:=&C{}
  19. c.init()
  20. this.Carry=[]C{*c}
  21. return
  22. }
  23. type C struct{
  24. state string
  25. }
  26. func (this *C)init(){
  27. this.state="1"
  28. return
  29. }
  30. func main(){
  31. a:=&A{}
  32. a.init()
  33. fmt.Printf("A:%v\n",a)
  34. p:=&a.Barry[0].Carry[0]
  35. p.state="2"
  36. fmt.Printf("A:%v\n",a)
  37. for _,v:=range a.Barry[0].Carry{
  38. if v.state=="2"{
  39. p=&v
  40. }
  41. }
  42. p.state="3"
  43. fmt.Printf("A:%v\n",a)
  44. }

答案1

得分: 0

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

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

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:

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

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:

确定