0Pricing
Go Academy · Lesson

The Stringer Interface

Customize how types print.

Default Struct Printing

By default, printing a struct with %v shows its raw fields. That is fine for debugging but not always reader-friendly.

package main

import "fmt"

type Color struct{ R, G, B int }

func main() {
    c := Color{255, 0, 0}
    fmt.Println(c)
}

The Stringer Interface

The fmt.Stringer interface has one method:

  • String() string

Any type that defines it controls how it appears when printed.

package main

import "fmt"

type Greeting struct{ Name string }

func (g Greeting) String() string {
    return "Hello, " + g.Name
}

func main() {
    fmt.Println(Greeting{"Ada"})
}

All lessons in this course

  1. Printf Verbs
  2. Sprintf and Fprintf
  3. The Stringer Interface
  4. Scanning Input
← Back to Go Academy