Why My Stringer Interface Method Isn't Invoked When Using fmt.Println()
You have a method String() defined on *Car, but when using fmt.Println(myCar), your object is a value and not a pointer. This behavior is due to fmt.Println() implicitly converting the myCar object to a value of type interface{} and then using a type switch to determine how to print it.
The type switch in the fmt package checks for a case of type fmt.Stringer. However, this check fails because Car (and not *Car) implements the String() method. Calling String() manually works because the compiler automatically converts myCar.String() to (&myCar).String(), supplying the necessary pointer.
To resolve this issue, you have two options:
fmt.Println(&myCar)
The above is the detailed content of Why Doesn't `fmt.Println()` Call My Stringer Method?. For more information, please follow other related articles on the PHP Chinese website!