This Go 1.27 Feature Confused Me at First!
Struct literal field selectors were extended in Go 1.27. If you would like to see a quick summary of all the changes in Go 1.27, check out this video: https://youtu.be/RboN0J87NrA 📝 Description Discover one of Go 1.27's most requested ergonomic upgrades: struct literal field selectors for embedded (promoted) fields. In this practical tutorial, we explore how this change lets you set promoted fields directly inside a struct literal, no more manual assignment after the fact. We break down how field promotion works with embedding, what happens when field names collide, and why this is a huge win for nested structs and table-driven tests. By the end, you'll know exactly when to use this pattern and where its sharp edges are. Here's what you will learn: • Understand field promotion and how embedded structs like http.Server expose their fields on the outer struct. • See struct literal field selectors in action, setting promoted fields directly when constructing a value. • Learn what happens with field shadowing when an embedded and outer struct share a field name. • Apply the pattern to deeply nested, JSON-tagged structs for cleaner, flatter initialization. • Use this feature to simplify table-driven tests with promoted fields. • Weigh the tradeoffs: better symmetry and readability for nested data vs. added complexity around shadowed fields. ⏳ Timestamps: 00:00 - Introduction 00:24 - Simple Case 04:27 - Same Name? 06:15 - Complex Case 10:26 - Unit Tests 12:09 - Summary 13:00 - Outro 🔗 Links: Proposal: https://github.com/golang/go/issues/9859 👋 Hey there! If you are new to this channel: Hey 👋 my name is Flo and I am a professional software engineer with a passion for coding in Golang, TypeScript, JavaScript, and Rust. This channel is where I share that passion and dive into the exciting world of software engineering. 📨 Support and Connect! Become a member. https://www.youtube.com/@FloWoelki/membership Discord: https://discord.gg/TnA7drJ X / Twitter: https://x.com/FlorianWoelki LinkedIn: https://www.linkedin.com/in/florian-woelki/ GitHub: https://github.com/FlorianWoelki 📝 Copyright Notice The original Go Gopher was designed by Renée French (Source: https://go.dev/blog/gopher License details: https://creativecommons.org/licenses/by/4.0/). The gopher appearing in this video and thumbnail has been modified from the original design and is based on an illustration from Maria Letta's free-gophers-pack (Source: https://github.com/MariaLetta/free-gophers-pack License: CC0 1.0 Public Domain https://creativecommons.org/publicdomain/zero/1.0/). #go #go127 #struct #literal #field #selector




Join the discussion
Sign in to join the discussion
Sign in