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 code
GoString() 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.
More Related questions...