golang 接口,为什么输出是 "bad error"?

golang interface and why output is "bad error"?

我尝试定义“错误”方法来键入“T”,但为什么值改变了??

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
}

如何解释这个案例?

这是来自 fmt 包的文档:

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. Another variant Println inserts blanks between operands and appends a newline.

因此,值 v 是使用 %v 打印的,它将使用 error 接口打印出来。

如果您使用 fmt.Printf("%d",v),它应该打印整数值。