Anonymous Fields and Embedded Structs
Explore the concept of anonymous fields and embedded structs in Go to understand how they enable composition and simulate inheritance. Learn how to assign values, manage naming conflicts, and compare structs, enhancing your struct manipulation skills in Go programming.
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:
In the above code, at line 4, we make a struct of type innerS containing two integer fields in1 and in2. At line 9, we make another struct of type outerS with two fields b (an integer) and c ...