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?
CodePudding user response:
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.