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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
