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
- Printf Verbs
- Sprintf and Fprintf
- The Stringer Interface
- Scanning Input