Go Structs (Part 1) — Anonymous Structs

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.

Blogger at codingbee.net

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Writing a very basic kubernetes mutating admission webhook

Everyone at a Software Conference

LATEST TRENDS IN FRONT END DEVELOPMENT 2022

Deploying React App on Microsoft Azure

Moti Network Airdrop

Web Developer Monthly 💻🚀 August 2019

New in BetterCloud: 5 Features Announced at Altitude 2019

Write for Us LoginRadius — Be a guest contributor and earn $200 per blog

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
Sher Chowdhury

Sher Chowdhury

Blogger at codingbee.net

More from Medium

What is go.mod?

Generics in Golang.

Golang Errgroup Package