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.
type Stringer interface { String() string }
Try it
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.
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
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
Stringmethod on*Tis only in the method set of*T. Printing a plainTvalue will not call it, as the second example shows. A value receiver works for bothTand*T. - Avoid infinite recursion. Inside
String(), never format the receiver with%vor%s; convert to the underlying type first, or print individual fields. - Keep it cheap and side-effect free.
fmtmay callString()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
Stringerare printed through it. - It does not affect JSON or
%d. UseMarshalTextfor encodings. - Not for parsing.
Stringis for display; pair it with a separate parse function if you need to round trip. - Sibling interfaces:
error(Error() string),fmt.GoStringerfor%#v, andfmt.Formatterfor full control over all verbs.
Related
- fmt verbs,
fmt.Printf(),fmt.Errorf() - Lessons: Methods, Interfaces, fmt in Depth