×

go · level 2 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Give a type a String method and fmt prints it your way.

Print a struct and you get its fields in curly brackets, like {Rex 3}. That is fine for you, but not for the people using your program. You can choose how your own type looks instead.

The fmt toolbox has an interface called . It asks for one method, String() string. If your type has it, fmt.Println, fmt.Printf with %v and fmt.Sprintf all call it and show what it returns.

You never write the word Stringer in your code. Having the method is enough to satisfy it. That is interfaces at work: fmt was written long before your type, yet it knows how to print it.

package main
import "fmt"
type Pet struct {
	Name string
	Age  int
}
func (p Pet) String() string {
	return fmt.Sprintf("%v (age %v)", p.Name, p.Age)
}
func main() {
	rex := Pet{Name: "Rex", Age: 3}
	fmt.Println(rex)
	fmt.Printf("Say hello to %v!\n", rex)
	pets := []Pet{rex, {Name: "Bella", Age: 5}}
	fmt.Println(pets)
}

Inside String, print the fields, never the whole value with %v, or String would call itself forever.