声明结构体字面量的数组

huangapple go评论70阅读模式
英文:

Declare array of struct literal

问题

如何声明一个结构体字面量的数组?

Go语言示例代码如下:

type Ping struct {
    Content []aContent
}

type aContent struct {
    Type       string
    Id         string
    Created_at int64
}

func main() {
    f := Ping{Content: []aContent{{Type: "Hello", Id: "asdf"}}}
    fmt.Println(f)
}

你可以在这里找到完整的代码:http://play.golang.org/p/-SyRw6dDUm

英文:

How do I declare an array of struct literal?

Go:

type Ping struct {
    Content []aContent
}

type aContent struct {
    Type 		string
    Id 			string
    Created_at 	int64
}

func main() {
    f := Ping{Content: []aContent{Type: "Hello", Id: "asdf"}}
    fmt.Println(f)
}

The code can be found here: http://play.golang.org/p/-SyRw6dDUm

答案1

得分: 40

你只需要再加一对大括号。

[]aContent{{Type: "Hello", Id: "asdf"}, {Type: "World", Id: "ghij"}}}
^ ^
这里 还有这里

这是一个用于数组的一对大括号,每个结构体在数组中都需要一对大括号。

英文:

You just need another pair of braces.

[]aContent{{Type: "Hello", Id: "asdf"}, {Type: "World", Id: "ghij"}}}
           ^                                                      ^
         here                                                    and here

That's one pair for the array, one for each struct in the array..

huangapple
  • 本文由 发表于 2014年9月24日 15:58:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/26011547.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定