liveBook · Manning

Stringer

As explained in Learn Go with Pocket-Sized Projects

The Stringer interface is the fmt convention satisfied by a type with a parameterless String method returning a string.

Stringer is the fmt convention satisfied by any type with a parameterless String() string method. Formatting and printing functions use that method to obtain the value’s native textual representation. section 5.2.1 section 6.4.3

Formatting a domain value

A currency can expose its code through String(): func (c Currency) String() string { return c.code } Passing a Currency to fmt.Print* functions then prints its code. Decimal can use the same convention to handle zero precision and pad fractional digits; Amount can combine the formatted number and currency code. section 6.4.3

Use Stringer when:

  • A value needs a readable default representation for fmt printing. section 5.2.1
  • A type’s textual form should be reusable without adding custom formatting knowledge for callers. section 5.2.1
  • A composite value should delegate formatting to its component values, as feedback does for each hint. section 5.2.1
type Stringer interface {
    String() string
}

The complete interface declaration makes the required method shape explicit. section 6.4.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines the one-method contract and demonstrates implementations, formatting behavior, composition, and receiver choices.
Examples
Demonstrates hint, feedback, Currency, Decimal, and Amount values with custom textual representations.
What you can do after
Apply it via fmt.Print* and formatting verbs to produce readable representations for custom Go types.
How it connects
Connects Stringer to interfaces, methods, fmt printing functions, strings.Builder, and pointer or value receivers.

Also explained in

Compare how 3 books explain Stringer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.