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))
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...
