I'm trying to define an array in struct in Go, devices array should have 3 items of type strings, but I can't find out how to print values of devices array
Below outputs "mismatched types string and [2]string". Any hints?
type Nodes struct {
Nodes []Node `json:"nodes"`
}
type Node struct {
devices [2]string `json:"devices"`
}
var nodes Nodes
fmt.Println("Device: %+v" + nodes.Nodes[i].devices)
Your error is because you're trying to concatenate a string
and a [2]string
:
"Device: %+v" + nodes.Nodes[i].devices
Specifically, "Device: %+v"
is a string, and nodes.Nodes[i].devices
is a [2]string
.
But at higher level, this is the result of improperly using fmt.Println
, made apparent by the use of a formatting verb %+v
, which makes no sense in the context of Println
. What you probably want is fmt.Printf
:
fmt.Printf("Device: %+v
", nodes.Nodes[0].devices)
You have to use fmt.Printf instead of Println :
fmt.Printf("Device: %+v", nodes.Nodes[i].devices)
Or you can do something like this :
for _, node := range nodes.Nodes {
for _, device := range node.devices {
fmt.Println("Device : " + device)
}
}
The output :
Device : Android
Device : iOS