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.
More Related questions...