Nesting Structs
07/26/21 08:30 Filed in: GO
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.
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:
The second way to set values is to use an instance of the inner struct and attach it to the outer struct.
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.
That's it for structs in GO.