Choosing how fmt prints your type
When you print a struct, fmt.Println shows its field values in braces, like {7 Bob}. That is fine while you test, but it is not what a user should see. You can choose how your type is printed by giving it a method called String that returns a string.
package main
import "fmt"
type Order struct {
ID int
Customer string
}
func (o Order) String() string {
return fmt.Sprintf("Order #%d for %s",
o.ID, o.Customer)
}
func main() {
o := Order{ID: 7, Customer: "Bob"}
fmt.Println(o)
fmt.Printf("%v\n", o)
fmt.Printf("%+v\n", o)
fmt.Println([]Order{o, {ID: 8, Customer: "Ann"}})
}
Output:
Order #7 for Bob
Order #7 for Bob
Order #7 for Bob
[Order #7 for Bob Order #8 for Ann]
Before fmt prints a value, it checks if the value has a method String() string. If it does, fmt prints what that method returns. This works with Println, with the %v and %+v verbs, and even for each order inside a slice. Without the method, %v would print {7 Bob} and %+v would print {ID:7 Customer:Bob}, as you saw in the Structs lesson.
The method builds its text with fmt.Sprintf from the Formatted Output lesson, which returns the text instead of printing it.
fmt.Stringer
This is the interface idea from the last lesson. The fmt package declares an interface called Stringer:
type Stringer interface {
String() string
}
Your Order never says that it is a Stringer. It has the right method, so it fits, and fmt treats it as one. Any type you write can do the same.
You can also call the method yourself when you need the text in a variable:
package main
import "fmt"
type Order struct {
ID int
Customer string
}
func (o Order) String() string {
return fmt.Sprintf("Order #%d for %s",
o.ID, o.Customer)
}
func main() {
o := Order{ID: 7, Customer: "Bob"}
line := "Next: " + o.String()
fmt.Println(line)
}
Output:
Next: Order #7 for Bob
Use a value receiver
In the Pointers lesson you learned to use pointer receivers for methods that change a struct. String should not change anything, and here a pointer receiver causes a surprise:
package main
import "fmt"
type Point struct {
X, Y int
}
func (p *Point) String() string {
return fmt.Sprintf("(%d, %d)", p.X, p.Y)
}
func main() {
p := Point{X: 1, Y: 2}
fmt.Println(p)
fmt.Println(&p)
}
Output:
{1 2}
(1, 2)
The method belongs to *Point, the pointer type. When you print p, fmt gets a copy of a Point value, and a plain Point has no String method. Only the pointer &p has it. Give String a value receiver, like (o Order) above, and it works for both.
One more trap: inside String, do not print the value itself with %v, like fmt.Sprintf("%v", o). That calls String again, which calls it again, without end, until the program crashes. Print the fields one by one instead.
In the exercise, write a String method so each order prints like #101 Alice: $80.