douhu8851 2018-12-15 11:07
浏览 1414

在Go中打印数组值

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)
  • 写回答

2条回答 默认 最新

  • doulu2011 2018-12-15 11:22
    关注

    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)
    
    评论

报告相同问题?