liveBook · Manning

Struct embedding

As explained in 100 Go Mistakes and How to Avoid Them

Type embedding is a Go language feature that promotes the fields and methods of an embedded type into the embedding type's method set and selector space.

Struct embedding promotes an embedded type’s fields and methods into the embedding struct’s selector space. A common mistake is treating promotion as harmless reuse: an embedded field can expose operations that should remain private. Embedding is not subclassing; promoted methods still retain the embedded type as their receiver. section 2.10

type Foo struct {
    Bar              #1
}
 
type Bar struct {
    Baz int
}

Here, Foo embeds Bar, so Bar’s Baz field can be accessed directly as Foo.Baz as well as through Foo.Bar.Baz; both paths identify the same field. section 2.10

Use embedding deliberately when deciding between promotion and encapsulation:

  • For data reuse, promotion can remove boilerplate: Foo.Baz is a direct alternative to Foo.Bar.Baz. section 2.10
  • For synchronization, embedding sync.Mutex exposes Lock and Unlock to clients through InMem, allowing callers to interfere with its locking policy. Keep the mutex in an unexported named field such as mu instead. section 2.10
  • For a wrapper such as Logger, use a named io.WriteCloser field and forwarding methods when you want explicit control; embed io.WriteCloser when promoted Write and Close behavior is intentional. section 2.10
  • Embedding also composes interfaces, as io.ReadWriter combines io.Reader and io.Writer, although the struct-field visibility issue concerns embedded fields in structs. section 2.10

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains selector promotion, receiver behavior, interface composition, and a mutex visibility failure, then stops short of broader embedding rules.
Examples
Uses Foo and Bar promotion, io.ReadWriter composition, an InMem mutex, and Logger forwarding or embedding.
What you can do after
Diagnose accidental method exposure and choose between embedded fields, named fields, and explicit forwarding methods.
How it connects
Connects promoted fields and methods with method sets, interfaces, encapsulation, and subclassing.

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 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.