Go Structs (Part 4) — Anonymous Fields and Promoted Fields

Image for post
Image for post
Photo by Peter Geo on Unsplash

When defining a struct, it’s actually possible to leave out the key name’s field. When doing so, the data type’s field (e.g. “string”) doubles up as the key-name.

This article is part of the Structs in Go series.

Let’s take a look at an example.

Image for post
Image for post
https://play.golang.org/p/TOsRX39ti4T

Lines 10–11: This looks a little weird here, but my intent is to have 2 entries, the person’s firstName and their age. Since I’m using anonymous fields, it means that the key-name to use access the firstName field is quite literally “string” and for age, it is “integer”.

Lines 20–21: We use the “string” and “int” key names to print out the respective values.

This technique doesn’t quite work if you want to have multiple fields of the same data type. In those scenarios you can resort to using a mix of anonymous fields and regular fields, for example let’s say I want to add a new “lastName” field to my struct:

Image for post
Image for post
https://play.golang.org/p/GtnZFf-gAE7

Anonymous Fields using Custom Data types

At this point, you might be thinking Anonymous Fields makes things weird and confusing, e.g. why is the age represented by the key-name “int”? I agree it is weird and not useful. That’s why in practice, it’s more useful to set up anonymous fields using custom data types (rather than primitive data types). To understand how this works, lets revisit the nested struct example, here it is again:

Image for post
Image for post

We can tweak this so to convert the address (line 18) field into an Anonymous Field:

Image for post
Image for post
https://play.golang.org/p/DQpoG7aNySn

This outputs:

Image for post
Image for post

Line 18: This was homeAddress address before, but we have now converted it to an anonymous field,address, which refers to the custom struck-based data type.

Line 38: Now we’re accessing the custom data type’s name, to access it’s content, which again looks more natural.

Line 39: This illustrates an extra bonus when setting up an anonymous field for a nested struct. That is that the child struct’s fields are promoted and become available at the parent level, i.e. they are Promoted Fields

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