liveBook · Manning

Struct embedding

As explained in Go in Action, Second Edition

Struct embedding is a Go language feature that embeds one struct type in another and promotes the embedded type's fields and methods.

Struct embedding lets one Go struct type promote another type’s fields and methods. It provides reuse through composition rather than class-based inheritance: there is no superclass, type hierarchy, virtual dispatch, or implicit “is-a” relationship. section 1.5 section 5.2

Use struct embedding to:

  • Compose larger domain types from simpler structs without maintaining an inheritance tree. section 1.5
  • Promote fields and methods while adding domain-specific behavior around an existing type. section 5.6.1
  • Combine embedding with interfaces so composed types can participate in flexible abstractions. section 5.7

Recipe measurements

A recipe application can embed a measurement type in metric and imperial measurement types, then add conversion or formatting behavior without changing the original measurement. Recipes can compose these measurements with ingredients and steps, scale them, convert them, and generate grocery lists. section 5.6.1 section 5.6.2

Figure 1.5 Inheritance vs. composition

Compare inheritance hierarchies with composition through embedded structs. section 1.5

How Go in Action, Second Edition covers it

How deep it goes
Explains promotion and composition, then applies them to measurements and recipes without detailing compiler resolution or embedding rules.
Examples
Demonstrates embedded metric and imperial measurements inside a recipe application with conversion, scaling, and grocery-list generation.
What it assumes
Assumes familiarity with Go types, structs, methods, and interfaces while contrasting embedding with object-oriented inheritance.
What you can do after
Build domain models that reuse fields and methods through composition and extend behavior with wrappers and interfaces.
How it connects
Connects struct embedding with composition, structs, methods, interfaces, polymorphism, and type safety.

Also explained in

Compare how 4 books explain struct embedding →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.