Go Structs (Part 3) — Nested Structs
Structs are used for storing primitive data types such as strings and integers. However structs are just as good for storing composite data types, such as arrays, slices, or even other structs. This means that structs can create rich hierarchical data structures, like those represented in json and yaml files.
This article is part of the Structs in Go series.
In this article we’re going to look at how to nest one struct inside another struct.
Running the above gives:
Lines 9–12: We defined a custom (struct) data type, called “address”
Line 18: This is the employee (struct) data type definition we’ve seen earlier, but with an additional key of “homeAddress”. We’ve set this key’s data type to the custom data type of “address”.
Lines 29–35: We create an “employee” variable, that contains a “address” nested inside it (line 34)
Line 37: The output of this shows the inner brackets, which indicates that we have one struct variable nested inside another.
Line 38: The .
operator let’s us traverse down the data structure to the value we’re interested in.
You can rewrite the above example so that it bypasses the need to create the “address1” variable:
Lines 26–32: Instead of passing a variable that contains the (“address” type) value, we’re now directly passing in the value itself. This is functionality the same as the previous example, but now code shows the nested nature more visually.