Back to Browse

Embedded Structs in Go

105 views
Mar 27, 2026
6:27

Embedded structs in Go let you compose types and reuse fields or methods without inheritance. In this Go Byte, you will learn how struct embedding works, what promoted fields and methods are, and how embedding differs from using a named field. What You'll Learn: - What struct embedding is and how it includes one struct in another without a field name - How promoted fields let you access inner data directly from the outer struct - The difference between embedding and using a named field - How methods on an embedded type are promoted to the outer type - When embedding improves clarity and when explicit named fields are better Conceptual Explanation: When you embed a struct, Go promotes its exported fields and methods to the outer struct. That means you can access user.City instead of user.Address.City, and you can call a promoted method like user.Full when it is defined on the embedded type. This is composition: you build larger types from smaller parts. If you use a named field instead, access stays explicit through that field, which can be clearer when the relationship is less central. How It Fits: Struct embedding is a common way to model real relationships in Go types while keeping code readable. It helps when a type is a natural part of another type and you want concise access. Named fields are still important when you want stronger separation. Understanding both patterns helps you design cleaner data models. Key Takeaways: - Embedding includes one struct in another without a field name - Embedded exported fields and methods are promoted to the outer struct - user.City is promoted access; user.Address.City is explicit named-field access - Embedding is composition, not inheritance - Choose embedding or named fields based on clarity of the relationship Try the challenge from the video before checking the solution. Links: Lesson folder on GitHub: https://github.com/GaryClarke/go-bytes/tree/main/struct-embedding Build your first Go app with me: https://www.garyclarke.tech/p/build-your-first-go-app Join the mailing list for new lessons and resources: https://content.garyclarke.tech/go-bytes-signup Follow on X/Twitter: https://twitter.com/garyclarketech Connect on LinkedIn: https://www.linkedin.com/in/garyclarketech/ Subscribe for more Go lessons. #golang #go #programming #coding #learnprogramming #gobytes

Download

1 formats

Video Formats

360pmp44.0 MB

Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.

Embedded Structs in Go | NatokHD