Home > Article > Backend Development > Why Does Go\'s `fmt.Println` Produce Unexpected Output When Embedding Types with Conflicting `String()` Methods?
In Go, embedding allows types to include fields and methods from another type within their own structure. However, when multiple embedded types define a method with the same name (such as String()), certain scenarios can lead to unexpected behavior.
Consider the following code:
type Engineer struct { Person TaxPayer Specialization string } type Person struct { Name string Age int } func (p Person) String() string { return fmt.Sprintf("name: %s, age: %d", p.Name, p.Age) } type TaxPayer struct { TaxBracket int } func (t TaxPayer) String() string { return fmt.Sprintf("%d", t.TaxBracket) } func main() { engineer := Engineer{ Person: Person{ Name: "John Doe", Age: 35, }, TaxPayer: TaxPayer{3}, Specialization: "Construction", } fmt.Println(engineer) }
When this code is executed, it produces the following output:
{name: John Doe, age: 35 3 Construction}
This result may seem confusing, as there are multiple String() methods defined within the embedded types Person and TaxPayer. However, the ambiguity is resolved by the following rules:
Removing the Person.String() method or the TaxPayer.String() method resolves the ambiguity, allowing the remaining String() method to be used for the default formatting.
The key takeaway from this behavior is that embedded types promote their String() methods only if there is a single, unambiguous method defined. If multiple methods exist, the embedding type does not have a promoted String() method, and the default formatting is used.
The above is the detailed content of Why Does Go\'s `fmt.Println` Produce Unexpected Output When Embedding Types with Conflicting `String()` Methods?. For more information, please follow other related articles on the PHP Chinese website!