Anonymous Fields and Embedded Structs
Explore how anonymous fields and embedded structs work in Go to help you compose types and simulate inheritance. Learn to assign values, handle name conflicts, and use anonymous structs for flexible data management.
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 (a float32 number). That’s not all. We also have two more fields that are anonymous fields. One is of type int (see line 13), and the other is of type innerS (see line 14). They are anonymous fields ...