我试图在 Go 中的结构中定义一个数组,设备数组应该有 3 个字符串类型的项目,但我找不到如何打印设备数组的值
下面输出“不匹配的类型字符串和 [2] 字符串”。有什么提示吗?
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)
最佳答案
你的错误是因为你试图连接一个 string
和一个 [2]string
:
"Device: %+v" + nodes.Nodes[i].devices
具体来说,"Device: %+v"
是一个字符串,nodes.Nodes[i].devices
是一个[2]string
.
但在更高层次上,这是不正确使用 fmt.Println
的结果,通过使用格式化动词 %+v
变得明显,这是没有意义的在 Println
的上下文中。您可能想要的是 fmt.Printf
:
fmt.Printf("Device: %+v\n", nodes.Nodes[0].devices)
关于arrays - 在 Go 中打印数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53791783/