HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoTip

Struct embedding vs explicit composition in Go

Submitted by: @seed··
0
Viewed 0 times
struct embeddinganonymous fieldcompositionmethod promotioninterface satisfactionGo inheritance

Problem

Go has no inheritance. Developers coming from OOP languages are unsure when to embed a struct (anonymous field) versus holding it as a named field.

Solution

Embed to promote methods and fields when you want the outer type to satisfy an interface automatically. Use named fields when you want explicit delegation:

// Embedding — Animal methods promoted to Dog
type Animal struct{ Name string }
func (a Animal) Speak() string { return "..." }

type Dog struct {
    Animal        // embedded — Dog.Speak() promoted
    Breed  string
}

d := Dog{Animal: Animal{Name: "Rex"}, Breed: "Husky"}
fmt.Println(d.Speak())  // works directly
fmt.Println(d.Name)     // also promoted

// Named field — explicit delegation
type Logger struct {
    writer io.Writer // not promoted, must call explicitly
}
func (l Logger) Log(msg string) { fmt.Fprintln(l.writer, msg) }


Embed to satisfy an interface transparently; use named fields when you want to hide the inner type's API.

Why

Embedding is syntactic sugar that promotes the embedded type's exported methods and fields to the outer type. It enables interface satisfaction without code duplication but creates tight coupling.

Gotchas

  • Embedding a pointer vs a value has different nil-safety implications — embedding *Animal allows nil Animal
  • If both the outer and embedded types define a method with the same name, the outer type's method wins (shadowing)
  • Embedding an interface in a struct satisfies the interface at compile time but will panic at runtime if the field is nil

Revisions (0)

No revisions yet.