dongyunqin7307 2018-08-13 20:06
浏览 6
已采纳

从范围生成的值具有相同的指针值[重复]

This question already has an answer here:

For these two struct

type A struct {
    Number *int
}

type B struct {
    Number int
}

If I want to loop on slice of B and assign the value of B.Number to new A.Number

func main() {
    aSlice := []A{}
    bSlice := []B{B{1}, B{2}, B{3}}
    for _, v := range bSlice {
        a := A{}
        a.Number = &v.Number
        aSlice = append(aSlice, a)
    }
}  

I will found that all aSlice a.Number is the same value and same pointer.

for _, v := range aSlice {
        fmt.Printf("aSlice Value %v Pointer %v
", *v.Number,v.Number)
    }

Will print
aSlice Value 3 Pointer 0x10414020
aSlice Value 3 Pointer 0x10414020
aSlice Value 3 Pointer 0x10414020

So does range only update the value of _,v in for loop and doesn't change the pointer ?

Full Code : https://play.golang.org/p/2wopH9HOjwj

</div>
  • 写回答

2条回答 默认 最新

  • dtftao7249656 2018-08-13 21:48
    关注

    It occurred because variable v is created at the beginning of the loop and doesn't change. So, every element in aSlice has a pointer to the same variable. You should write this:

    for _, v := range bSlice {
        a := A{}
        v := v
        a.Number = &v.Number
        aSlice = append(aSlice, a)
    }
    

    Here you create at every iteration new variable with its own pointer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 公众号如何实现点击超链接后自动发送文字
  • ¥15 用php隐藏类名和增加类名
  • ¥15 算法设计与分析课程的提问
  • ¥15 用MATLAB汇总拟合图
  • ¥15 智能除草机器人方案设计
  • ¥15 对接wps协作接口实现消息发送
  • ¥15 SQLite 出现“Database is locked” 如何解决?
  • ¥15 已经加了学校的隶属邮箱了,为什么还是进不去github education?😭
  • ¥15 求会做聚类,TCN的朋友有偿线上指导。以下是目前遇到的问题
  • ¥100 无网格伽辽金方法研究裂纹扩展的程序