Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the fmt.Stringer interface and how do you implement it?
The fmt.Stringer interface is the standard Go convention for providing a human-readable string representation of a type. It is used automatically by fmt.Print, fmt.Println, and %v / %s format verbs.
// Interface definition (in the fmt package) type Stringer interface { String() string } // Custom type implementing Stringer type Color int const ( Red Color = iota Green Blue ) func (c Color) String() string { switch c { case Red: return "Red" case Green: return "Green" case Blue: return "Blue" default: return fmt.Sprintf("Color(%d)", int(c)) } } fmt.Println(Red) // Red (not '0') fmt.Printf("%v\n", Green) // Green fmt.Printf("%s\n", Blue) // Blue // Another example: Point type type Point struct{ X, Y float64 } func (p Point) String() string { return fmt.Sprintf("(%.2f, %.2f)", p.X, p.Y) } p := Point{3.14159, 2.71828} fmt.Println(p) // (3.14, 2.72) // GoStringer (fmt.GoStringer) â %#v verb, Go syntax representation type Foo struct{ X int } func (f Foo) GoString() string { return fmt.Sprintf("Foo{X: %d}", f.X) } fmt.Printf("%#v\n", Foo{42}) // Foo{X: 42}
Implementing Stringer makes debugging significantly easier: log output, error messages, and test failure messages show meaningful names rather than raw integer or struct values. It is a lightweight interface with large practical benefit — implementing it should be a habit for any named type that appears in logs or user-facing output.
More Related questions...