英文:
Golang, Go : implicitly calling interface function?
问题
我已经翻译好了,以下是翻译的内容:
我有这个函数
func (e *MyError) Error() string {
return fmt.Sprintf("AT %v, %s", e.When, e.What)
}
但是
如下所示,我从未调用它,但最终输出中为什么会调用它?
type MyError struct {
When time.Time
What string
}
func (e *MyError) Error() string {
return fmt.Sprintf("AT %v, %s", e.When, e.What)
}
func run() error {
return &MyError{
time.Now(), "它没有工作",
}
}
func main() {
if err := run(); err != nil {
fmt.Println(err)
}
}
请注意,这是您提供的代码和问题的翻译。如果您有任何其他问题,请告诉我。
英文:
http://play.golang.org/p/xjs-jwMsr7
I have this function
func (e *MyError) Error() string {
return fmt.Sprintf("AT %v, %s", e.When, e.What)
}
But
as you see below, I never called it but how come it is called in the final output?
type MyError struct {
When time.Time
What string
}
func (e *MyError) Error() string {
return fmt.Sprintf("AT %v, %s", e.When, e.What)
}
func run() error {
return &MyError{
time.Now(), "it didn't work",
}
}
func main() {
if err := run(); err != nil {
fmt.Println(err)
}
}
答案1
得分: 1
fmt.Println和pkg/fmt中的其他函数会分析传递给它的对象。
如果是一个错误对象,该函数会调用传递对象的.Error()方法,并打印Error()方法返回的字符串。
详细信息请参见源代码。代码中的部分如下所示:
switch v := p.field.(type) {
case error:
// ...
p.printField(v.Error(), verb, plus, false, depth)
return
// ...
}
在类型切换语句中检查传递对象的类型,如果该对象实现了error接口,则使用v.Error()作为值。
英文:
fmt.Println and the other functions in pkg/fmt analyze the objects passed to it.
If it is an error, the function calls .Error() on the passed object and prints the string
returned by Error().
See the source for details. The code says:
switch v := p.field.(type) {
case error:
// ...
p.printField(v.Error(), verb, plus, false, depth)
return
// ...
}
The type of the passed object is checked in a type switch statement and in case of the object
implementing the error interface, v.Error() is used as value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论