liveBook · Manning

Structural typing

As explained in Go in Action, Second Edition

Structural typing determines interface compatibility from the methods a type provides rather than from an explicit declaration of implementation.

Structural typing determines interface compatibility from the methods a type provides. In Go, no explicit implementation declaration is required, and the compiler verifies satisfaction before execution. section 5.5

This supports practical abstractions: formatting can depend on String(), while measurement types become interchangeable when they provide ToImperial() and ToMetric(). section 5.5

// --- Convertible Interface ---

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

A Convertible interface specifies the method shape that metric and imperial measurement types must provide. section 5.5

Measurement conversion

MetricWeight, ImperialWeight, MetricVolume, and ImperialVolume can satisfy Convertible through matching conversion methods, allowing conversion code to work against the interface rather than a concrete type. section 5.5

How Go in Action, Second Edition covers it

How deep it goes
Explains interface satisfaction and compiler checking, then demonstrates Stringer and Convertible implementations.
Examples
Demonstrates String methods for units and conversion methods for metric and imperial weights and volumes.
What you can do after
Apply it via Go interfaces to define interchangeable types and receive compile-time errors for missing methods.
How it connects
Connects interfaces with polymorphism, compile-time checking, Stringer, formatting, and measurement conversion.

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.