Go Structs (Part 3) — Nested Structs

Image for post
Image for post
Photo by Iza Gawrych on Unsplash

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.

Image for post
Image for post

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:

Image for post
Image for post

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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store