我想我有这些类型:
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吗?
显然,我不想仅仅为迭代更改结构,更详细的解决方案不是解决方案.
这必须是一个菜鸟问题.在从范围循环中获取元素后,我试图在struct/instance(Aa)中增加一个var.看起来我得到了元素的副本,如何在范围循环中引用元素本身?
package main
import "fmt"
type A struct {
a int
s string
}
func main() {
var es = []A {
A{
a:0,
s:"test",
},
A{
a:1,
s:"test1",
},
}
for _,e:=range es {
fmt.Printf("%v\n", e)
e.a++
}
for _,e:=range es {
fmt.Printf("%v\n", e)
e.a++
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
{0 test}
{1 test1}
{0 test}
{1 test1}
Run Code Online (Sandbox Code Playgroud)
期望的输出:
{0 test}
{1 test1}
{1 test}
{2 test1}
Run Code Online (Sandbox Code Playgroud)
提前致谢