Why Doesn\'t `fmt.Println` Use My Struct\'s `String()` Method?

Susan Sarandon
Release: 2024-11-22 05:03:15
Original
391 people have browsed it

Why Doesn't `fmt.Println` Use My Struct's `String()` Method?

Uncovering the Mystery: Why fmt.Println Skips String() Methods in Structs

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)
}
Copy after login

Expected Output:

{bar bar} [bar] bar
Copy after login
Copy after login

Actual Output:

{[0x176f44] 0x176f44} [bar] bar
Copy after login

Unraveling the Reasons

There are two key factors behind this behavior:

  • Unexported types: The bar type is unexported, meaning it can only be used within the same package. When unexported types are embedded in exported structs like foo, their methods are also unexported.
  • Unexported fields: The fields b and bb in foo are unexported, which means their String() method cannot be accessed by fmt.Println.

Illuminating the Solution

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)
}
Copy after login

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
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template