Golang / GoLang Basics Interview Questions
What is the fmt.Stringer interface and how does it control how a type is printed?
The fmt package defines the Stringer interface: a type that implements String() string controls how it appears when printed with fmt.Println, fmt.Printf("%v"), and related functions. Implementing error works the same way for error messages.
// fmt.Stringer interface: // type Stringer interface { String() string } type Direction int const ( North Direction = iota South; East; West ) func (d Direction) String() string { return [...]string{"North", "South", "East", "West"}[d] } fmt.Println(North) // North (not: 0) fmt.Printf("%v\n", East) // East fmt.Printf("%s\n", West) // West // Another example: Point with custom format type Point struct{ X, Y float64 } func (p Point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.X, p.Y) } p := Point{3.5, 7.2} fmt.Println(p) // (3.5, 7.2) fmt.Printf("%v\n", p) // (3.5, 7.2) // TRAP: infinite recursion inside String() // func (p Point) String() string { // return fmt.Sprintf("%v", p) // calls String() again â stack overflow! // } // FIX: cast to a non-Stringer type // return fmt.Sprintf("%v", struct{ X, Y float64 }(p))
More Related questions...