Method Invocation Failure with Interface Conversion in fmt.Println
When attempting to use fmt.Println to print a value of a custom type, the expected method invocation of the type's String() method may not occur. This issue arises when the value is passed as a value rather than a pointer.
Consider the example code:
import "fmt" type Car struct { year int make string } func (c *Car) String() string { return fmt.Sprintf("{make:%s, year:%d}", c.make, c.year) } func main() { myCar := Car{year: 1996, make: "Toyota"} fmt.Println(myCar) // Value-based object }
In this instance, the expected String() method of Car will not be called when fmt.Println is used with a value of type Car. Instead, the value will be formatted using the default Go formatting mechanism.
To resolve this issue and ensure that the custom String() method is invoked regardless of whether the object is a value or a pointer, the following options are available:
fmt.Println(&myCar) // Pointer-based object
By adhering to these guidelines, you can reliably invoke the String() method and control the formatting of custom types within fmt.Println.
The above is the detailed content of Why Doesn't `fmt.Println` Always Call My Custom Type's `String()` Method?. For more information, please follow other related articles on the PHP Chinese website!