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.",
},
},
},
}