Composition Over Inheritance

Composition Over Inheritance in Go: In a language built on inheritance you describe a new kind of worker by naming their parent. A is an , which is a .

The Analogy: The Toolbelt Instead of the Family Tree

In a language built on inheritance you describe a new kind of worker by naming their parent. A SecurityGuard is an Employee, which is a Person. Behaviour flows down the family tree, and when it works it feels like a bargain: you write six lines and inherit six hundred. The tree tells you what a thing is, and being something is how it gets its abilities.

The trouble is that a family tree has one line of descent and real jobs do not. The night-shift guard who also drives the van and holds a first-aid certificate does not belong to a single lineage. So the trees grow deeper, then abstract base classes appear to hold the shared bits, then multiple inheritance arrives with the diamond problem in tow, and finally interfaces-with-default-methods are bolted on to paper over the whole arrangement. Every layer is a workaround for the original decision that abilities are inherited rather than acquired.

Go removed the tree. A Go type is a toolbelt. You clip on the tools you need and each tool keeps its own name, so the guard who drives has a Driver on the belt and you reach driving behaviour by naming that tool. Go's one concession to convenience is that clipping a tool on without a label promotes its methods to the belt itself: write Driver with no field name and guard.Drive() works directly. That is embedding, and it is the entire mechanism. There is no parent, no super, and nothing inherited that you cannot point at.

This sounds like a downgrade until you notice what it buys. There is no hidden state arriving from three levels up. Every behaviour a type has is traceable to a field you can see in its declaration. And the question of whether a type fits a slot is answered by an interface, satisfied structurally, usually declared by the code that consumes it rather than the code that implements it. The rest of this lesson is the mechanics of the belt - promotion, shadowing, ambiguity, and the absence of virtual dispatch - and then the judgement call that matters: when to clip a tool on and when to give it a name.


Syntax or Core Structure

Embedding is a field declaration with the name left off.

// brigade.go
package main

import "fmt"

type Engine struct {
	Kind string
	HP   int
}

func (e Engine) Start() string {
	return fmt.Sprintf("%s engine spinning up (%d hp)", e.Kind, e.HP)
}
func (e Engine) Describe() string { return "engine: " + e.Kind }

type Radio struct{ Band string }

func (r Radio) Describe() string { return "radio: " + r.Band }

type Car struct {
	Engine // embedded: no field name, so its methods and fields promote
	Radio  // also embedded, and it also has a Describe method
	Name   string
}

// Without this method, c.Describe() would not compile: two candidates at
// the same depth is an ambiguous selector.
func (c Car) Describe() string {
	return "car " + c.Name + " with " + c.Engine.Describe()
}

func main() {
	c := Car{Engine: Engine{"diesel", 148}, Radio: Radio{"FM"}, Name: "Kombi"}

	fmt.Println(c.Start())          // promoted from Engine
	fmt.Println(c.Describe())       // Car's own method shadows both embedded ones
	fmt.Println(c.Radio.Describe()) // qualifying is always unambiguous
	fmt.Println(c.HP, c.Band)       // fields promote too

	// var e Engine = c            // compile error: Car is not an Engine
	fmt.Println(c.Engine.HP == c.HP)
}

Output:

diesel engine spinning up (148 hp)
car Kombi with engine: diesel
radio: FM
148 FM
true

Four things happened there. Start was promoted, so Car has a method it never declared. Describe collided, and Car's own declaration at depth zero resolved the collision by shadowing both. The fields HP and Band promoted exactly like the methods did, and c.HP is the same storage as c.Engine.HP. And the commented-out line is the one that separates this from inheritance: Car has an Engine and is not one.


Technical Depth: Embedding, Promotion and the Missing Virtual Call

Embedding looks enough like inheritance that people import their old expectations, and every one of those expectations is wrong in a way that matters.

BehaviourClass inheritanceGo embedding
Assignable to the base typeYes, a Car can be passed as an EngineNo, and []Engine will not accept a Car
A base method calling an overrideYes, that is virtual dispatchNo, Engine.Describe only ever sees an Engine
Reaching the outer value from insideThe implicit receiver is the whole objectImpossible, the embedded value has no back pointer
ConstructionParent constructors chain automaticallyYou initialise each embedded field yourself
Multiple parentsForbidden, or fraughtAny number, and collisions are resolved by depth
Access controlprotected sits between public and privateNo such level, only exported and unexported
Typical shapeDeep treesFlat, one or two levels

The promotion rules, precisely

Promotion is a name-resolution rule, not a code-generation trick. The compiler builds the set of names reachable from the outer type and picks by depth.

  • A field or method of an embedded type is reachable at depth one. Embed a type that itself embeds another and you reach the inner names at depth two, and so on with no limit.
  • The shallowest name wins. A name declared directly on the outer type is at depth zero and shadows anything embedded, at any depth.
  • Two names tied at the shallowest depth are ambiguous. It is not an error for the type to have them; it is an error to use the unqualified selector. Car without its own Describe compiles perfectly well until someone writes c.Describe().
  • That has a consequence people trip over: an ambiguous name is not in the type's method set, so the type quietly fails to satisfy any interface requiring it. The error surfaces at the assignment, far from the embedding.
  • Qualifying by the embedded type's name always works and always means exactly one thing: c.Engine.Describe().
  • The implicit field name is the type's unqualified name. Embed io.Reader and the field is Reader. Embed *Engine and the field is still Engine. You therefore cannot embed both bytes.Buffer and some other package's Buffer in the same struct.

Method sets and the nil embedded pointer

This is the trap that costs the most debugging time, and it comes in two flavours.

type Counter struct{ n int }

func (c *Counter) Inc()     { c.n++ }
func (c Counter) Value() int { return c.n }

type ByValue struct{ Counter }  // has a Counter
type ByPointer struct{ *Counter } // has a pointer to one

func main() {
	v := ByValue{}          // the Counter is a usable zero value
	v.Inc()                 // fine: v is addressable, so (&v.Counter).Inc()
	fmt.Println(v.Value())  // 1

	p := ByPointer{}        // the embedded pointer is nil
	p.Inc()                 // panic: invalid memory address
}

Embedding by value gives you a working zero value for free. Embedding a pointer gives you a type whose zero value panics on first use, which means it needs a constructor and needs it documented. Separately, embedding Counter by value puts Inc in *ByValue's method set but not in ByValue's, because Inc needs a pointer receiver. So ByValue{} will not satisfy an interface{ Inc() } while &ByValue{} will.

Embedding an interface: the four-line decorator

A struct can embed an interface, not just a concrete type. The struct then satisfies that interface by forwarding every method to whatever value was stored, and you override only the ones you care about. The standard library's sort.Reverse is the whole technique in four lines:

type reverse struct {
	Interface // whatever the caller passed in
}

func (r reverse) Less(i, j int) bool { return r.Interface.Less(j, i) }

func Reverse(data Interface) Interface { return &reverse{data} }

Len and Swap are never mentioned and never need to be. This is the decorator pattern with no boilerplate, and it is forward compatible: add a method to the interface and every decorator built this way still compiles. That last property is a double-edged sword, and the Real World Example below is built around exactly where the edge cuts.

The one hazard is that the embedded interface can be nil. reverse{} compiles, satisfies sort.Interface, and panics on the first forwarded call. Any type that embeds an interface needs a constructor, or a documented promise that the caller fills the field.

Composition in the standard library

DeclarationWhat the embedding buys
type ReadWriter interface { Reader; Writer }Interface embedding: the method set is the union of the two contracts
type ReadWriter struct { *Reader; *Writer } in bufioTwo pointer embeddings, so one value offers both buffered APIs
type reverse struct { Interface } in sortOverride one method, forward the rest
type T struct { common; ... } in testingT and B share Log, Error and Fatal without either being the other
struct { sync.Mutex; m map[string]int }A guarded map where v.Lock() reads naturally

That last row is the one to think twice about. Embedding sync.Mutex in an exported type publishes Lock and Unlock as part of your API, and callers will use them, which means you can never change your locking strategy. In exported types, give the mutex a name: mu sync.Mutex. Embed it only in package-internal types where the convenience is worth nothing to anyone outside.

Interfaces belong to the consumer

Composition only pays off if the seams are in the right places, and in Go a seam is an interface. Two habits make the difference.

  • Keep them small. One or two methods is normal. io.Reader has one method and is the most reused type in the language. A ten-method interface can only ever be satisfied by the thing it was extracted from.
  • Declare them where they are used, not where they are implemented. The package that needs to read bytes declares interface{ Read([]byte) (int, error) }; the package that produces bytes just has a Read method and never imports the consumer. This is how Go avoids the dependency arrow pointing the wrong way, and it is why accept interfaces, return structs is the standard advice: a constructor returning *memStore lets each caller narrow it to whatever contract that caller actually needs.
  • When you do want a compile-time check that a type still satisfies a contract, state it as a declaration: var _ Store = (*memStore)(nil). It costs nothing at runtime and it fails the build the moment a signature drifts.

Real World Example: Three Layers Over One Interface

A key-value store gains a tenant prefix, call counting and a read-only mode. In a class hierarchy that is three subclasses fighting over one super. Here it is one implementation and three small wrappers, stacked at the call site.

// store.go
package main

import (
	"errors"
	"fmt"
	"sort"
	"strings"
	"sync"
)

type Store interface {
	Get(key string) (string, error)
	Put(key, value string) error
	Delete(key string) error
}

var ErrNotFound = errors.New("not found")

// memStore is the only type here that actually stores anything.
type memStore struct {
	mu sync.Mutex // named, not embedded: locking is not part of the API
	m  map[string]string
}

func newMemStore() *memStore { return &memStore{m: make(map[string]string)} }

func (s *memStore) Get(key string) (string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	v, ok := s.m[key]
	if !ok {
		return "", fmt.Errorf("get %q: %w", key, ErrNotFound)
	}
	return v, nil
}

func (s *memStore) Put(key, value string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.m[key] = value
	return nil
}

func (s *memStore) Delete(key string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if _, ok := s.m[key]; !ok {
		return fmt.Errorf("delete %q: %w", key, ErrNotFound)
	}
	delete(s.m, key)
	return nil
}

var _ Store = (*memStore)(nil)

The three wrappers. Note how differently they use the embedded interface.

// readOnly overrides the two writes and forwards Get without naming it.
type readOnly struct{ Store }

func (readOnly) Put(key, value string) error { return errors.New("store is read only") }
func (readOnly) Delete(key string) error     { return errors.New("store is read only") }

// prefixed namespaces every key. It overrides all three methods, so the
// embedding exists only to reach the wrapped store.
type prefixed struct {
	Store
	prefix string
}

func (p prefixed) Get(key string) (string, error) { return p.Store.Get(p.prefix + key) }
func (p prefixed) Put(key, value string) error    { return p.Store.Put(p.prefix+key, value) }
func (p prefixed) Delete(key string) error        { return p.Store.Delete(p.prefix + key) }

// counted tallies calls. It holds a mutex, so its methods take a pointer
// receiver and it must never be copied.
type counted struct {
	Store
	mu     sync.Mutex
	counts map[string]int
}

func newCounted(s Store) *counted {
	return &counted{Store: s, counts: make(map[string]int)}
}

func (c *counted) hit(name string) {
	c.mu.Lock()
	c.counts[name]++
	c.mu.Unlock()
}

func (c *counted) Get(key string) (string, error) { c.hit("Get"); return c.Store.Get(key) }
func (c *counted) Put(key, value string) error    { c.hit("Put"); return c.Store.Put(key, value) }
func (c *counted) Delete(key string) error        { c.hit("Delete"); return c.Store.Delete(key) }

func (c *counted) report() string {
	c.mu.Lock()
	defer c.mu.Unlock()
	names := make([]string, 0, len(c.counts))
	for n := range c.counts {
		names = append(names, n)
	}
	sort.Strings(names) // map order is random, printed order must not be
	parts := make([]string, 0, len(names))
	for _, n := range names {
		parts = append(parts, fmt.Sprintf("%s=%d", n, c.counts[n]))
	}
	return strings.Join(parts, " ")
}

The stack is assembled in three lines, and the order of those lines is the design.

func main() {
	base := newMemStore()
	metrics := newCounted(base)
	var s Store = prefixed{Store: metrics, prefix: "tenant-7/"}

	must(s.Put("colour", "blue"))
	must(s.Put("size", "large"))

	v, err := s.Get("colour")
	fmt.Println("get colour:", v, err)

	_, err = s.Get("missing")
	fmt.Println("get missing:", err)
	fmt.Println("is ErrNotFound:", errors.Is(err, ErrNotFound))

	// Reading the raw store shows the namespacing the caller never sees.
	raw, _ := base.Get("tenant-7/colour")
	fmt.Println("raw key:", raw)

	// Freeze the very same stack for a read only phase.
	frozen := readOnly{Store: s}
	fmt.Println("frozen put:", frozen.Put("colour", "red"))
	v, _ = frozen.Get("colour")
	fmt.Println("frozen get:", v)

	fmt.Println("calls:", metrics.report())
}

func must(err error) {
	if err != nil {
		panic(err)
	}
}

Output:

get colour: blue <nil>
get missing: get "tenant-7/missing": not found
is ErrNotFound: true
raw key: blue
frozen put: store is read only
frozen get: blue
calls: Get=3 Put=2

Only memStore touches a map. The three wrappers are between four and twenty lines each, none of them imports or mentions the others, and main decides the order. That order is not cosmetic. counted sits inside prefixed here, so it tallies the calls that reached storage, with fully qualified keys. Move it outside and it tallies what the caller asked for. With a cache in the stack those two numbers diverge, and the gap between them is your hit rate. Delete never appears in the report because it was never called, which is why the report is built from the map rather than from a fixed list.

The interesting difference is between readOnly and prefixed, because they take opposite sides of one trade. readOnly genuinely relies on forwarding: it names two methods and inherits the third. Add a fourth method to Store and readOnly still compiles - and that is also the bug, because a new Truncate would forward straight through the read-only gate in silence. prefixed overrides everything, so its embedding is only a way to reach the wrapped value. Give it a named field instead - next Store - and adding Truncate breaks the build, which for prefixed is exactly what you want, since an unprefixed key would leak across tenants. Embedding an interface versus naming the field is a decision about what should happen when that interface grows: forward silently, or fail loudly. Pick per wrapper, and write down why.

Error identity survives the whole stack. errors.Is(err, ErrNotFound) is true three layers up because memStore wrapped with %w and every layer above returned the error untouched. A wrapper that "improves" an error with errors.New(err.Error()) severs that chain and every errors.Is above it starts returning false, silently. Forwarding a value unchanged is the default behaviour of a decorator, and it is worth protecting.

What none of this needed: a base class, an abstract method, or a super call. What it cannot do is dispatch downward. memStore cannot call prefixed's override, because memStore has never heard of it and there is no vtable to consult. When a lower layer genuinely must call into a behaviour supplied by a higher one, you pass that behaviour in explicitly, as a function field or a small interface field. That is the template-method pattern rewritten as composition, and taking it up to package scale is the next lesson: the plugin pattern.


Common Mistakes

  1. Reading embedding as "is a". Car embeds Engine but is not an Engine, so func test(e Engine) will not take a Car and []Engine will not hold one. If you need the substitution, that is what an interface is for.
  1. Expecting virtual dispatch. Engine.Describe cannot call Car.Describe. The embedded value has no idea it is embedded and no pointer back to the outer struct. Any design that needs the inner layer to call outward has to be passed the outward behaviour as a value.
  1. A nil embedded pointer or nil embedded interface. struct{ *Counter } and struct{ Store } both have zero values that compile, satisfy their interfaces, and panic on the first call. Either embed by value or supply a constructor.
  1. Embedding sync.Mutex in an exported type. It publishes Lock and Unlock to every caller, who will start using them, and now your locking strategy is frozen forever. Name the field mu in anything exported.
  1. Treating an ambiguous selector as a harmless warning. Two embedded types with the same method name at the same depth means that name is absent from the method set, so the type silently stops satisfying interfaces that require it - and the error appears at the assignment, nowhere near the embedding.
  1. Copying a struct that embeds a mutex or a wait group. c := *counted copies the lock in whatever state it was in. go vet's copylocks check catches this, which is one reason to run go vet in CI rather than only go test.
  1. Embedding when a named field would be clearer. Every promoted method becomes part of your type's method set and therefore part of its API. Embedding a type with thirty methods to reuse one of them exports the other twenty-nine by accident.
  1. Declaring the interface in the implementing package. A Storer interface sitting next to memStore, with exactly one implementation, is a class hierarchy in disguise. Move it to the package that calls it and shrink it to the methods that package uses.
  1. Forgetting that embedded fields flatten in encoding/json. An embedded struct's fields marshal as if they were declared on the outer type, so adding an embedding changes your wire format. Giving the embedded field a tag name, or a real field name, nests it instead.
  1. Using an embedded interface as a fake abstract class. Leaving the field nil to mean "subclass must implement this" turns a compile-time obligation into a runtime panic. If a behaviour is required, make it a constructor parameter.
  1. Embedding three levels deep because promotion allows it. The compiler resolves depth four happily; a reader tracing x.Flush() through four type declarations does not. Flat compositions with named fields read better than deep ones with promoted names.

Best Practices

  • Default to a named field. Embed only when you specifically want the promotion, and when the promoted method set is one you are happy to own publicly.
  • Keep interfaces small and declare them in the package that consumes them. Accept interfaces as parameters and return concrete types from constructors.
  • Give every type that embeds a pointer or an interface a constructor, so the zero value is never the thing callers get by accident.
  • Choose deliberately between an embedded interface and a named field in each wrapper, based on whether a future method should forward silently or break the build.
  • Use pointer receivers on any type holding a mutex, and let go vet enforce that it is never copied.
  • Assert contracts at compile time with var _ Iface = (*Type)(nil) rather than trusting that a signature change will be noticed.
  • Resolve collisions explicitly. If two embedded types share a method name and you want one of them, declare that method on the outer type and forward, so the choice is visible in the source.
  • Forward values unchanged in a decorator unless you are deliberately transforming them. In particular, wrap errors with %w and never rebuild them from their text.

Practice Exercises

  1. Add a cached wrapper to the example that keeps the last value read and serves it without calling through. Place counted once outside cached and once inside it, and print both reports for the same sequence of calls. Explain in two sentences what each number now measures.
  1. Change prefixed from embedding Store to holding next Store, then add a Keys() ([]string, error) method to the Store interface. Note precisely which wrappers stop compiling and which keep working, and argue which of the two outcomes you would want for a tenant-isolation wrapper and which for a metrics wrapper.
  1. Build a type embedding two structs that both have a Close() error method. Try to assign it to an io.Closer and read the compiler error. Then fix it three ways - an outer Close that closes both, a qualified call at the use site, and named fields instead of embedding - and say which you would ship.
  1. Take ByValue and ByPointer from the method-set section and write a program that shows all four cases: which of ByValue{}, &ByValue{}, ByPointer{} and &ByPointer{&Counter{}} satisfy interface{ Inc() }, and which panic when called. Write your predictions down first.