Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize an array of structs inside a nested struct in golang

Tags:

json

arrays

go

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

like image 431
mquemazz Avatar asked Feb 12 '15 13:02

mquemazz


People also ask

How do I create a struct inside a struct in Golang?

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.

Can you put an array inside a struct?

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.

How do you initialize a nested struct?

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.


1 Answers

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) } 
like image 174
Not_a_Golfer Avatar answered Sep 24 '22 21:09

Not_a_Golfer