Go Structs (Part 1) — Anonymous Structs

Sher Chowdhury
2 min readDec 21, 2020
Photo by Kelli McClintock on Unsplash

With a regular struct, you define the struct, and then you use that struct definition to declare variables. Anonymous Structs on the other hand lets you create struct-based data-type variables without needing to define the struct.

This article is part of the Structs in Go series.

First, here’s a reminder of what a regular struct looks like, we define the struct (lines 10–16), and then we declare variables using that struct definition (lines 18–24) and (lines 26–32).

https://play.golang.org/p/DFHwg12jJFN

This outputs:

So the values stored in the “emp1” and “emp2” variables, belongs to our custom (struct-derived) data type, “employee”.

Anonymous structs on the other hand lets you create struct-based variables without needing to define the struct.

https://play.golang.org/p/Id5-lOFMuYV

Lines 10–16: This time, the struct’s definition actually forms part of the “emp1” variable’s declaration.

Lines 24: Since anonymous structs don’t have a name, then data type is displayed as the struct’s actual definition.

Since the struct definition is embedded into the variable declaration, it means that the anonymous struct definition is restricted to declaring 1 variable. That can be useful in some scenarios.

So if you want to declare multiple variables with the same anonymous struct definition, then you can either repeat the struct definition code block per variable declaration (which means code duplication), or just use regular structs instead.

--

--