Golang接口和为什么输出是”bad error”?

huangapple go评论84阅读模式
英文:

golang interface and why output is "bad error"?

问题

我尝试定义一个类型为"T"的"Error"方法,但为什么值会改变?

type T int

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

func main() {
	var v interface{} = T(5)
    fmt.Println(v) //输出:bad error,而不是5
}

如何解释这个情况?

英文:

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?

答案1

得分: 1

这是来自fmt包文档的内容:

如果操作数实现了error接口,将调用Error方法将对象转换为字符串,然后根据所需的动词(如果有)进行格式化。

另外:

对于每个类似Printf的函数,还有一个不带格式的Print函数,它等效于对每个操作数使用%v。另一个变体Println在操作数之间插入空格并追加一个换行符。

因此,值v将使用%v进行打印,它将使用error接口将其打印出来。

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

英文:

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.

huangapple
  • 本文由 发表于 2022年3月20日 23:40:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/71548187.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定