Anonymous Fields and Embedded Structs
In the first part of this lesson, you'll study how to make structs with nameless fields and how to use them. In the second part, you'll see how to embed a struct inside another struct and use it.
We'll cover the following
Definition
Sometimes, it can be useful to have structs that contain one or more anonymous (or embedded) fields that are fields with no explicit name. Only the type of such a field is mandatory, and the type is then also the field’s name. Such an anonymous field can also be itself a struct, which means structs can contain embedded structs. This compares vaguely to the concept of inheritance in OO-languages, and as we will see, it can be used to simulate a behavior very much like inheritance. This is obtained by embedding or composition. Therefore, we can say that in Go composition is favored over inheritance.
Consider the following program:
Get hands-on with 1400+ tech skills courses.