Golang / GoLang Interfaces and Object Oriented Interview Questions
How do the fmt.Stringer and error interfaces work together and how do you avoid infinite recursion?
Types often implement both fmt.Stringer (String() string) and error (Error() string). A subtle trap: inside String(), calling fmt.Sprintf("%v", e) on the receiver causes infinite recursion because %v checks for Stringer and calls String() again.
type AppError struct {
Code int
Message string
}
// BUGGY String() — infinite recursion
// func (e AppError) String() string {
// return fmt.Sprintf("%v", e) // calls e.String() → infinite loop
// }
// CORRECT: format fields directly, not the receiver
func (e AppError) String() string {
return fmt.Sprintf("AppError[%d]: %s", e.Code, e.Message)
}
// Implements both error and Stringer
func (e AppError) Error() string { return e.String() }
// Usage
err := AppError{Code: 404, Message: "not found"}
fmt.Println(err) // uses Stringer: AppError[404]: not found
fmt.Println(err.Error()) // error: AppError[404]: not found
var e error = err // also satisfies error interface
fmt.Println(e) // same output via error.Error()
// Safe pattern: convert to a plain type inside String()
type Point struct{ X, Y int }
func (p Point) String() string {
// Using struct literal — NOT the receiver — avoids recursion
return fmt.Sprintf("(%d, %d)", p.X, p.Y)
}Detection: the Go runtime detects some infinite-recursion panics (stack overflow), but they can be hard to trace. Always format individual fields, not the receiver itself, inside String() and Error(). Use %d, %s, %f directly on the fields.
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...
