go · level 2 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Printing the weather. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
type Temp struct {
Celsius int
}
func (t Temp) String() string {
return fmt.Sprintf("%v°C", t.Celsius)
}
func main() {
today := Temp{Celsius: 21}
fmt.Println("Today:", today)
fmt.Println("Raw:", today.Celsius)
}
your turn
Your turn. Fill the bookshelf.
Name the method that fmt looks for, finish the line it returns with the right field, then put a book you like on the shelf.
output
press run to see what happens
fix it
The playing card prints as a jumble. Can you fix it?
output
press run to see what happens
- The card prints as {Queen hearts}, so
fmtis ignoring the method. What exactly doesStringerask for? StringerwantsString() string, a method that returns text. This one prints and returns nothing.- Make line 7 func (c Card) String() string { and line 8 return c.Rank + " of " + c.Suit, then run.
nailed it
your types print beautifully. :D
- A
String() stringmethod satisfiesfmt.Stringer. fmtcallsStringwhenever it prints your type.- Return the text from
Stringinstead of printing it.
new words in your collection
- Stringer
This lesson isn’t saved. A free account remembers every lesson you finish.