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








