liveBook · Manning

Polymorphism

As explained in Go in Action, Second Edition

Polymorphism is the ability to treat values of different concrete types through a shared interface or abstraction.

Polymorphism lets different concrete types be used through shared behavior. In Go, interfaces provide this abstraction without inheritance or complex type hierarchies, keeping domain code flexible, composable, and testable. section 5.5

Go applies polymorphism through a small, behavior-focused contract:

  • Define an interface containing the required methods, such as ToImperial and ToMetric on Convertible. section 5.5
  • Let unrelated concrete types satisfy the interface implicitly by implementing those methods. section 5.5
  • Use any implementing type wherever the interface is expected, regardless of its underlying representation. section 5.5
  • Extend the domain by adding new measurement types without changing code that depends only on the interface. section 5.5
// --- Convertible Interface ---

type Convertible interface {
    ToImperial() Measurement
    ToMetric() Measurement
}

The Convertible interface captures the shared conversion behavior that allows metric weight, imperial weight, metric volume, and imperial volume to participate uniformly. section 5.5

Recipe measurements

A recipe application represents measurements with specialized metric and imperial types. Each type implements conversion methods: metric weights produce ounces, imperial weights produce grams, metric volumes produce pints, and imperial volumes produce liters. When a recipe is built, scaled, converted, and summarized, the surrounding code can work with the shared behavior rather than each concrete measurement implementation. section 5.5 section 5.6.2

How Go in Action, Second Edition covers it

How deep it goes
Explains interface contracts and demonstrates concrete measurement conversions, while emphasizing design flexibility rather than runtime internals.
Examples
Demonstrates String methods, Convertible measurements, recipe scaling, unit conversion, and grocery-list generation.
What it assumes
Builds on named types, structs, methods, composition, and Go’s type system.
What you can do after
Apply it via Go interfaces to write flexible code that accepts multiple implementations and supports later domain extensions.
How it connects
Connects interfaces with methods, structs, composition, inheritance, type assertions, and type switches.

Also explained in

Compare how 9 books explain polymorphism →

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.