dongyunqin7307 2018-08-13 12: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 13: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条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 fluent设置了自动保存后,会有几个时间点不保存
  • ¥20 激光照射到四象线探测器,通过液晶屏显示X、Y值
  • ¥15 这怎么做,怎么在我的思路下改下我这写的不对
  • ¥50 数据库开发问题求解答
  • ¥15 安装anaconda时报错
  • ¥20 如何用Python处理单元格内连续出现的重复词语?
  • ¥15 小程序有个导出到插件方式,我是在分包下引入的插件,这个export的路径对吗,我看官方文档上写的是相对路径
  • ¥20 希望有人能帮我完成这个设计( *ˊᵕˋ)
  • ¥100 将Intptr传入SetHdevmode()将Intptr传入后转换为DEVMODE的值与外部代码不一致
  • ¥50 基于ERA5数据计算VPD