liveBook · Manning

Stringer

As explained in Go in Action, Second Edition

Stringer is a Go interface conventionally satisfied by a type that provides a String method for custom textual formatting.

Stringer is the conventional Go interface for values that provide a String() method returning custom textual formatting. Formatting functions such as fmt.Printf use that result automatically, making domain values more readable. section 5.5

A type satisfies Stringer structurally: it needs the required method, but no explicit declaration. Go checks satisfaction at compile time, while the -er naming convention makes single-method interfaces recognizable. section 5.5

Formatting measurement units

A Unit type can implement String() to return familiar abbreviations such as “g”, “kg”, “oz”, “lb”, “L”, and “gal”. Unknown values can fall back to their underlying string representation. section 5.5

type Stringer interface {
    String() string
}

Inspect the minimal Stringer interface definition before comparing it with a concrete Unit implementation. section 5.5

How Go in Action, Second Edition covers it

How deep it goes
Explains the method contract, naming convention, structural satisfaction, and compile-time verification.
Examples
Formats measurement units using common abbreviations and an underlying-string fallback.
What you can do after
Apply it by implementing String() so Go formatting functions display domain values meaningfully.
How it connects
Connects Stringer with interfaces, structural typing, fmt.Printf, Reader, and Writer.

Also explained in

Compare how 3 books explain Stringer →

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.