liveBook · Manning

Stringer

As explained in Go in Practice, Second Edition

fmt.Stringer is a Go standard-library interface implemented by types that provide a parameterless String method returning a string.

fmt.Stringer is a structural Go interface: any type with a parameterless String method returning string satisfies it without an explicit declaration. section 13.1.2

Check Stringer conformance in two practical ways:

  • Use a type assertion when testing a value, such as v.(fmt.Stringer), which also performs the interface conversion. section 13.1.2
  • Use reflection when the target interface must be selected or inspected at runtime; obtain the interface type and call Implements. section 13.1.2

Checking a custom type

A *Name type with String returning First plus Last is reported as a Stringer but not as an io.Writer. Running the example prints both results.

How Go in Practice, Second Edition covers it

How deep it goes
Defines the method shape and demonstrates assertion and reflection checks, without developing broader formatting behavior.
Examples
Demonstrates Stringer with a Name type and compares it against io.Writer using runnable assertion and reflection examples.
What it assumes
Assumes basic Go types and interfaces while clarifying that interfaces require matching methods rather than declarations.
What you can do after
Apply type assertions or the reflect package to determine whether values or types implement Stringer.
How it connects
Connects interfaces with type assertions, reflection, structural typing, and io.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 Practice, Second Edition. The section links point to the parts of the book it draws on.