迭代时更改值 [英] Change values while iterating

查看:114
本文介绍了迭代时更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下几种类型:

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.

我很希望能够做到:

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

但由于attr不是指针,因此无法正常工作,我必须这样做:

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"
    }
}

有更简单或更快速的方法吗?是否可以直接从range获取指针?

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.

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

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

因此,范围使用a[i]作为数组/切片的第二个值,这实际上意味着 值将被复制,从而使原始值不可更改.

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

因此,您唯一可以做的就是使用指针或索引,如jnml和peterSO所建议的那样.

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

这篇关于迭代时更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆