Home >Backend Development >Golang >Why Does fmt.Println Invoke Car.String() for Pointers but Not Values?
Invoked String() for Printing Objects with fmt.Println
When dealing with fmt.Println and Stringer interfaces, understanding the type conversion process is crucial.
In the provided code, Car.String() is invoked when handling pointers, but not when using values. This is because fmt.Println coerces both pointers and values into an interface{} type.
fmt then performs type switching to determine how to print the value. For values implementing fmt.Stringer (with a String method returning a string), it prints the result of that method. However, for values with a String method defined on the pointer type, the type switching fails.
Resolution:
To resolve this, either implement String on the Car type or pass a pointer to fmt.Println, as seen below:
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) // Passing the pointer explicitly }
Alternatively, you can use a custom type assertion to manually invoke String, but this approach is not recommended:
func main() { myCar := Car{year: 1996, make: "Toyota"} if v, ok := myCar.(fmt.Stringer); ok { fmt.Println(v.String()) // Manually invoking String } }
By addressing the type conversion behavior of fmt.Println, you can effectively control how objects are formatted, regardless of their value or pointer nature.
The above is the detailed content of Why Does fmt.Println Invoke Car.String() for Pointers but Not Values?. For more information, please follow other related articles on the PHP Chinese website!