且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

迭代时更改值

更新时间:2022-10-15 16:12:10

不,您想要的缩写是不可能的.

这样做的原因是 range 从您正在迭代的切片中复制值.关于范围的规范 说:

范围表达式第一个值第二个值(如果存在第二个变量)数组或切片 a [n]E、*[n]E 或 []E 索引 i int a[i] E

因此,range 使用 a[i] 作为数组/切片的第二个值,这实际上意味着值被复制,使原始值不可触碰.

此行为由以下代码演示:

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

代码为您打印了完全不同的内存位置,用于范围内的值和实际值切片中的值:

0xf84000f010 vs. 0x7f095ed0bf680xf84000f014 与 0x7f095ed0bf680xf84000f018 与 0x7f095ed0bf68

所以你唯一能做的就是使用指针或索引,正如 jnml 和 peterSO 已经提出的那样.

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.

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.