在golang中迭代时更改值

Den*_*ret 137 arrays for-loop go

我想我有这些类型:

type Attribute struct {
    Key, Val string
}
type Node struct {
    Attr []Attribute
}
Run Code Online (Sandbox Code Playgroud)

并且我想迭代我的节点的属性来改变它们.

我本以为能够做到:

for _, attr := range n.Attr {
    if attr.Key == "href" {
        attr.Val = "something"
    }
}
Run Code Online (Sandbox Code Playgroud)

但由于attr不是指针,这不起作用,我必须这样做:

for i, attr := range n.Attr {
    if attr.Key == "href" {
        n.Attr[i].Val = "something"
    }
}
Run Code Online (Sandbox Code Playgroud)

有更简单或更快的方式吗?有可能直接从指针中获取指针range吗?

显然,我不想仅仅为迭代更改结构,更详细的解决方案不是解决方案.

nem*_*emo 133

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

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

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
Run Code Online (Sandbox Code Playgroud)

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

以下代码演示了此行为:

x := make([]int, 3)

x[0], x[1], x[2] = 1, 2, 3

for i, val := range x {
    println(&x[i], "vs.", &val)
}
Run Code Online (Sandbox Code Playgroud)

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

0xf84000f010 vs. 0x7f095ed0bf68
0xf84000f014 vs. 0x7f095ed0bf68
0xf84000f018 vs. 0x7f095ed0bf68
Run Code Online (Sandbox Code Playgroud)

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

  • 想到这一点的一种方法是分配值会导致副本.如果你看到val:= x [1],那么val就是x [1]的副本就完全不足为奇了.不要将范围视为做某些特殊事物,而是要记住范围的每次迭代都是通过分配索引和值变量开始的,而不是导致复制的范围. (14认同)

pet*_*rSO 33

你似乎在寻求与此相当的东西:

package main

import "fmt"

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

func main() {

    n := Node{
        []Attribute{
            {"key", "value"},
            {"href", "http://www.google.com"},
        },
    }
    fmt.Println(n)

    for i := 0; i < len(n.Attr); i++ {
        attr := &n.Attr[i]
        if attr.Key == "href" {
            attr.Val = "something"
        }
    }

    fmt.Println(n)
}
Run Code Online (Sandbox Code Playgroud)

输出:

{[{key value} {href http://www.google.com}]}
{[{key value} {href something}]}
Run Code Online (Sandbox Code Playgroud)

这避免Attribute了以切片边界检查为代价创建类型值的可能较大的副本.在您的示例中,类型Attribute相对较小,两个string切片引用:64位体系结构计算机上的2*3*8 = 48个字节.

你也可以简单地写:

for i := 0; i < len(n.Attr); i++ {
    if n.Attr[i].Key == "href" {
        n.Attr[i].Val = "something"
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,使用range子句获取等效结果的方法是:创建副本但最小化切片边界检查,是:

for i, attr := range n.Attr {
    if attr.Key == "href" {
        n.Attr[i].Val = "something"
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 遗憾的是,如果`someMap` 是`map`,`value := &amp;someMap[key]` 将不起作用 (2认同)

Pau*_*kin 20

我会调整你的最后一个建议,并使用范围的索引版本.

for i := range n.Attr {
    if n.Attr[i].Key == "href" {
        n.Attr[i].Val = "something"
    }
}
Run Code Online (Sandbox Code Playgroud)

对于我来说,n.Attr[i]在测试Key行和设置行中明确地引用它似乎更简单Val,而不是attr用于一个和n.Attr[i]另一个.


zzz*_*zzz 14

例如:

package main

import "fmt"

type Attribute struct {
        Key, Val string
}

type Node struct {
        Attr []*Attribute
}

func main() {
        n := Node{[]*Attribute{
                &Attribute{"foo", ""},
                &Attribute{"href", ""},
                &Attribute{"bar", ""},
        }}

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

        for _, v := range n.Attr {
                fmt.Printf("%#v\n", *v)
        }
}
Run Code Online (Sandbox Code Playgroud)

操场


产量

main.Attribute{Key:"foo", Val:""}
main.Attribute{Key:"href", Val:"something"}
main.Attribute{Key:"bar", Val:""}
Run Code Online (Sandbox Code Playgroud)

替代方法:

package main

import "fmt"

type Attribute struct {
        Key, Val string
}

type Node struct {
        Attr []Attribute
}

func main() {
        n := Node{[]Attribute{
            {"foo", ""},
            {"href", ""},
            {"bar", ""},
        }}

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

        for _, v := range n.Attr {
                fmt.Printf("%#v\n", v)
        }
}
Run Code Online (Sandbox Code Playgroud)

操场


输出:

main.Attribute{Key:"foo", Val:""}
main.Attribute{Key:"href", Val:"something"}
main.Attribute{Key:"bar", Val:""}
Run Code Online (Sandbox Code Playgroud)