Home > Article > Backend Development > Why Doesn\'t `fmt.Println` Use My Struct\'s `String()` Method?
Imagine a dilemma: you define a String() method for a struct to provide custom printing behavior, but fmt.Println seems to ignore it, leaving you with unreadable output. This is the case with the following code:
package main import ( "fmt" ) type bar struct { } func (b bar) String() string { return "bar" } type foo struct { b []*bar bb *bar } func main() { f := foo{b: []*bar{&bar{}}, bb: &bar{}} fmt.Println(f, f.b, f.bb) }
Expected Output:
{bar bar} [bar] bar
Actual Output:
{[0x176f44] 0x176f44} [bar] bar
There are two key factors behind this behavior:
To fix this, we need to make both the bar type and the foo fields exported. Here's the corrected code:
type Bar struct { } func (b Bar) String() string { return "bar" } type foo struct { B []Bar BB Bar } func main() { f := foo{B: []Bar{Bar{}}, BB: Bar{}} fmt.Println(f) }
Playground: https://play.golang.org/p/OhoIcB7cA3
This ensures that both Bar and its String() method are exported, allowing fmt.Println to utilize it. Consequently, we obtain the desired output:
{bar bar} [bar] bar
In conclusion, remember to export both the types and fields involved in the String() method to enable fmt.Println to leverage this powerful custom formatting feature.
The above is the detailed content of Why Doesn\'t `fmt.Println` Use My Struct\'s `String()` Method?. For more information, please follow other related articles on the PHP Chinese website!