Stringers

One of the most ubiquitous interfaces is Stringer defined by the fmt package.

  1. type Stringer interface {
  2. String() string
  3. }

A Stringer is a type that can describe itself as a string. The fmt package (and many others) look for this interface to print values.

stringer.go

  1. package main
  2. import "fmt"
  3. type Person struct {
  4. Name string
  5. Age int
  6. }
  7. func (p Person) String() string {
  8. return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
  9. }
  10. func main() {
  11. a := Person{"Arthur Dent", 42}
  12. z := Person{"Zaphod Beeblebrox", 9001}
  13. fmt.Println(a, z)
  14. }