无法修改数组中的结构体吗?

huangapple go评论94阅读模式
英文:

Impossible to modify struct inside array?

问题

我刚开始学习golang,我有以下的代码:

https://play.golang.org/p/OBsf9MRLD8

package main

import (
	"encoding/json"
	"os"
)

type ResourceUsage struct {
	Type string
}
type Node struct {
	Resources []ResourceUsage
}

func main(){
	encoder := json.NewEncoder(os.Stdout)
	nodes := make([]Node, 2)
	nodes[0] = Node{}
	nodes[1] = Node{}
	
	for _,n := range nodes {
		n.Resources = append(n.Resources, ResourceUsage{Type: "test"})
	}
	encoder.Encode(nodes)
}

我希望它打印出:

[{"Resources":[{"Type":"test"}]},{"Resources":[{"Type":"test"}]}]

但实际上我得到的是:

[{"Resources":null},{"Resources":null}]

我该如何实现预期的输出?

英文:

I'm just starting to learn golang and I have the following code:

https://play.golang.org/p/OBsf9MRLD8

package main

import (
	"encoding/json"
	"os"
)

type ResourceUsage struct {
	Type string
}
type Node struct {
	Resources []ResourceUsage
}

func main(){
	encoder := json.NewEncoder(os.Stdout)
	nodes := make([]Node, 2)
	nodes[0] = Node{}
	nodes[1] = Node{}
	
	for _,n := range nodes {
		n.Resources = append(n.Resources, ResourceUsage{Type: "test"})
	}
	encoder.Encode(nodes)
}

I was hoping it to print

[{"Resources":[{"Type:"test"}]},{"Resources":[{"Type:"test"}]}]

But instead I get:

[{"Resources":null},{"Resources":null}]

How can I accomplish the expected output?

答案1

得分: 16

结构体在范围循环中是被复制的。你需要通过索引来访问。

for i := range nodes {
    nodes[i].Resources = append(nodes[i].Resources, ResourceUsage{Type: "test"})
}

你也可以选择使用指针,这样就不会复制数据。

nodes := make([]*Node, 2)
nodes[0] = &Node{}
nodes[1] = &Node{}

@Kaedys 指出,你不能取迭代值的地址。

for _, v := range nodes {
    &v // 错误
}
英文:

Structs are copied in range loops. You need to access by index.

for i := range nodes {
    nodes[i].Resources = append(nodes[i].Resources, ResourceUsage{Type: "test"})
}

You could also choose to use pointers, which would not copy data.

nodes := make([]*Node, 2)
nodes[0] = &Node{}
nodes[1] = &Node{}

@Kaedys points out, you can't take the address of the iterated value.

for _, v := range nodes {
    &v // mistake
}

huangapple
  • 本文由 发表于 2017年1月18日 04:19:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/41706212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定