[英]Initialize an array of structs inside a nested struct in golang
I am wondering how can I define and initialize and array of structs inside a nested struct, for example: 我想知道如何在嵌套结构中定义和初始化结构和数组,例如:
type State struct {
id string `json:"id" bson:"id"`
Cities
}
type City struct {
id string `json:"id" bson:"id"`
}
type Cities struct {
cities []City
}
Now how can I Initialize such a structure and if someone has a different idea about how to create the structure itself. 现在我如何初始化这样的结构,如果有人对如何创建结构本身有不同的想法。
Thanks 谢谢
In your case the shorthand literal syntax would be: 在您的情况下,简写文字语法将是:
state := State {
id: "CA",
Cities: Cities{
[]City {
{"SF"},
},
},
}
Or shorter if you don't want the key:value syntax for literals: 如果您不想要文字的键:值语法,则更短:
state := State {
"CA", Cities{
[]City {
{"SF"},
},
},
}
BTW if Cities doesn't contain anything other than the []City, just use a slice of City. 顺便说一句,如果城市不包含除[]城市以外的任何内容,只需使用一片城市。 This will lead to a somewhat shorter syntax, and remove an unnecessary (possibly) layer: 这将导致语法稍微缩短,并删除不必要的(可能)层:
type State struct {
id string `json:"id" bson:"id"`
Cities []City
}
type City struct {
id string `json:"id" bson:"id"`
}
func main(){
state := State {
id: "CA",
Cities: []City{
{"SF"},
},
}
fmt.Println(state)
}
Full example with everything written out explicitly: 完整示例,明确写出所有内容:
state := State{
id: "Independent Republic of Stackoverflow",
Cities: Cities{
cities: []City{
City{
id: "Postington O.P.",
},
},
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.