Nesting Structs

A Struct Within a Struct



As in other languages, a struct can house another struct. First, I define the structs that will be embedded, and then use their types as the types within the parent struct. Because GO sets all fields to zero values, all of the fields within structs, whether nested or not, are likewise initialized.


Screen Shot 2021-07-26 at 8.41.46 AM

Also, as in other languages I can set the values of the fields within the struct in two basic ways. First, I can set use the outer struct and set the values directly:


Screen Shot 2021-07-26 at 8.49.35 AM



The second way to set values is to use an instance of the inner struct and attach it to the outer struct.




Screen Shot 2021-07-26 at 8.57.47 AM


Anonymous Structs




GO also allows for anonymous structs that are child structs without a referencing field name. Because, the child has no field name, the child fields are treated as if belonging to the parent, and referenced that way. Anonymous structs are also called embedded structs.



Screen Shot 2021-07-26 at 9.02.59 AM


That's it for structs in GO.




This site does not track your information.