Home >Backend Development >Golang >Why Doesn't `fmt.Println()` Call My Stringer Method?

Why Doesn't `fmt.Println()` Call My Stringer Method?

Linda Hamilton
Linda HamiltonOriginal
2024-12-04 08:34:12549browse

Why Doesn't `fmt.Println()` Call My Stringer Method?

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:

  • Implement String() on Car instead of *Car.
  • Always pass a pointer to fmt.Println():
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!

Statement:
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