Home > Backend Development > Golang > Why Does fmt.Println Print 'bad error' Instead of 5 When a Custom Type Implements the Go Error Interface?

Why Does fmt.Println Print 'bad error' Instead of 5 When a Custom Type Implements the Go Error Interface?

Barbara Streisand
Release: 2024-12-22 11:37:13
Original
111 people have browsed it

Why Does fmt.Println Print

Understanding the Behavior of Go Interfaces for Error Handling

In the Go programming language, interfaces provide a powerful mechanism for defining contracts between types. One such contract is the "Error" interface, which allows types to represent errors. This article explores a specific scenario where defining an "Error" method for a custom type leads to unexpected output.

The Problem:

Consider the following code snippet:

type T int

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

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

When you run this code, the output is "bad error" instead of the expected integer value 5. Why is this happening?

The Answer:

This behavior can be explained by understanding how fmt.Println handles values. According to the fmt package documentation, if an operand implements the "Error" interface, its Error method is invoked to convert the object to a string for printing. Since the custom type T implements this interface, its Error method returns "bad error," which is printed instead of the integer value.

The Resolution:

To print the integer value of T, you can use the fmt.Printf function with the appropriate format specifier. For example:

fmt.Printf("%d", v) //output: 5
Copy after login

Alternately, you can define a custom String() method for type T to control the output format when using fmt.Println:

type T int

func (t T) String() string {
    return strconv.Itoa(int(t))
}

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

The above is the detailed content of Why Does fmt.Println Print 'bad error' Instead of 5 When a Custom Type Implements the Go 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