Home > Backend Development > Golang > Why Does `fmt.Println` Print 'bad error' Instead of the Integer Value When a Type Implements the `error` Interface?

Why Does `fmt.Println` Print 'bad error' Instead of the Integer Value When a Type Implements the `error` Interface?

Susan Sarandon
Release: 2024-12-09 07:46:07
Original
766 people have browsed it

Why Does `fmt.Println` Print

Why Does an Interface Return ""bad error"" for a Custom Type's Error Method?

In Go, an interface can be used to define methods for a type. When an object implements an interface, it provides an implementation for each of the methods defined by that interface.

Consider the following example:

type T int

func (t T) Error() string {
    return "bad error"
}

func main() {
    var v interface{} = T(5)
    fmt.Println(v) // Output: "bad error"
}
Copy after login

In this example, the Error method is defined for the type T. However, when the value v is printed using fmt.Println, the output is "bad error" instead of the expected integer value 5. To understand this behavior, let's refer to the fmt package documentation:

  • If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).
  • For each Printf-like function, there is also a Print function that takes no format and is equivalent to saying %v for every operand.

In this case, the fmt.Println function is used, which is equivalent to fmt.Printf("%v", v). Here's an explanation of what happens:

  • Since T implements the error interface, the Error method is invoked on the value v.
  • The Error method returns the string "bad error."
  • This string is then formatted by the %v verb and printed as the output.

To print the integer value of v instead, you can use fmt.Printf("%d",v).

The above is the detailed content of Why Does `fmt.Println` Print 'bad error' Instead of the Integer Value When a Type Implements the `error` Interface?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template