Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the difference between fmt.Stringer and fmt.GoStringer?
Go's fmt package supports two string-representation interfaces for types. They serve different audiences and contexts:
| Interface | Method | Format Verb | Purpose |
|---|---|---|---|
| fmt.Stringer | String() string | %v, %s | Human-readable output for logs, CLI, user-facing text |
| fmt.GoStringer | GoString() string | %#v | Go-syntax representation for debugging — shows how to reproduce the value |
type Color struct{ R, G, B uint8 }
// Stringer — human readable
func (c Color) String() string {
return fmt.Sprintf("#%02X%02X%02X", c.R, c.G, c.B)
}
// GoStringer — Go syntax
func (c Color) GoString() string {
return fmt.Sprintf("Color{R: %d, G: %d, B: %d}", c.R, c.G, c.B)
}
c := Color{255, 128, 0}
fmt.Printf("%v\n", c) // #FF8000 (uses String())
fmt.Printf("%s\n", c) // #FF8000
fmt.Printf("%#v\n", c) // Color{R: 255, G: 128, B: 0} (uses GoString())
// Without GoString, %#v uses default Go syntax:
// main.Color{R:0xff, G:0x80, B:0x0}
// Practical use: panic messages, test failure output, %#v in debugging
// GoString makes the output directly copy-pasteable as Go codeGoString() is particularly valuable in test failure messages: when a test prints %#v of an unexpected value, the output can be copied directly into the test as the expected value — saving debugging time.
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...
