英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论