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