Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท fmt Package

Go fmt.Stringer interface

Reference for fmt.Stringer in Go: define a String method so Println, %v and %s print your type your way, plus value vs pointer receivers and recursion traps.

fmt.Stringer is an interface with a single method, String() string. When a value that implements it is printed with %v, %s or by Println, fmt calls String() and prints the result instead of the default representation.

It is how you give your own types a readable text form: enums that print as names, money that prints with a currency sign, IDs that print in a standard format.

Go
type Stringer interface {
	String() string
}

Try it

Go An enum that prints its name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Pointer receivers and the recursion trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
type Stringer interface {
	String() string
}

There is nothing to register. Any type with a String() string method satisfies the interface automatically.

Printing call Uses String()?
fmt.Println(v), %v, %s Yes
%q Yes, and the result is quoted
%x, %X Yes, applied to the returned string
%d and other number verbs No, the underlying number prints
%+v, %#v %+v uses it; %#v uses GoString() instead if present

Edge cases: if a type has both Error() string and String() string, Error() wins. A panic inside String() is caught by fmt and shown as %!v(PANIC=String method: ...), except for a nil pointer receiver, which prints <nil>.

Usage notes

  • Receiver type matters. A String method on *T is only in the method set of *T. Printing a plain T value will not call it, as the second example shows. A value receiver works for both T and *T.
  • Avoid infinite recursion. Inside String(), never format the receiver with %v or %s; convert to the underlying type first, or print individual fields.
  • Keep it cheap and side-effect free. fmt may call String() many times, even from concurrent goroutines, so do not lock or mutate state in it.
  • Nested values are covered. Slices, maps and struct fields that implement Stringer are printed through it.
  • It does not affect JSON or %d. Use MarshalText for encodings.
  • Not for parsing. String is for display; pair it with a separate parse function if you need to round trip.
  • Sibling interfaces: error (Error() string), fmt.GoStringer for %#v, and fmt.Formatter for full control over all verbs.