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
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. Go language allows nested structure.
A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.
Initializing nested Structuresstruct person { char name[20]; int age; char dob[10]; }; struct student { struct person info; int rollno; float marks[10]; } struct student student_1 = { {"Adam", 25, 1990}, 101, 90 }; The following program demonstrates how we can use nested structures.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With