perhaps? 2013-04-11 09:19 采纳率: 100%
浏览 215
已采纳

在戈朗中迭代时更改值

Let's suppose I have these types:

type Attribute struct {
    Key, Val string
}
type Node struct {
    Attr []Attribute
}

and that I want to iterate on my node's attributes to change them.

I would have loved to be able to do:

for _, attr := range n.Attr {
    if attr.Key == "href" {
        attr.Val = "something"
    }
}

but as attr isn't a pointer, this wouldn't work and I have to do:

for i, attr := range n.Attr {
    if attr.Key == "href" {
        n.Attr[i].Val = "something"
    }
}

Is there a simpler or faster way? Is it possible to directly get pointers from range?

Obviously I don't want to change the structures just for the iteration and more verbose solutions are no solutions.

转载于:https://stackoverflow.com/questions/15945030/change-values-while-iterating-in-golang

  • 写回答

4条回答 默认 最新

  • 撒拉嘿哟木头 2013-04-11 15:11
    关注

    No, the abbreviation you want is not possible.

    The reason for this is that range copies the values from the slice you're iterating over. The specification about range says:

    Range expression                          1st value             2nd value (if 2nd variable is present)
    array or slice  a   [n]E, *[n]E, or []E   index    i  int       a[i]       E
    

    So, range uses a[i] as its second value for arrays/slices, which effectively means that the value is copied, making the original value untouchable.

    This behavior is demonstrated by the following code:

    x := make([]int, 3)
    
    x[0], x[1], x[2] = 1, 2, 3
    
    for i, val := range x {
        println(&x[i], "vs.", &val)
    }
    

    The code prints you completely different memory locations for the value from range and the actual value in the slice:

    0xf84000f010 vs. 0x7f095ed0bf68
    0xf84000f014 vs. 0x7f095ed0bf68
    0xf84000f018 vs. 0x7f095ed0bf68
    

    So the only thing you can do is to either use pointers or the index, as already proposed by jnml and peterSO.

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

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助