golang interface and why output is "bad error"?

Issue

I try to define "Error" method to type "T", but why value changed??

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
}

How to explain this case?

Solution

This is from the documentation of the fmt package:

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).

Also:

For each Printf-like function, there is also a Print function that takes no format and is equivalent to saying %v for every operand. Another variant Println inserts blanks between operands and appends a newline.

So, the value v is printed using %v, which will use the error interface to print it out.

If you use fmt.Printf("%d",v), it should print the integer value.

Answered By – Burak Serdar

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.