douye1940 2015-04-06 07:09
浏览 36
已采纳

GoLang错误/接口机制

Firstly, I am not quite sure if this problem is more relevant to error, or to interface in GoLang

I am catching up the GoLang by following the tutorial. The question came with this tutorial page

It is a basic demonstration of the error interface. When I change the code a bit like this, I got confused:

package main

import (
    "fmt"
    "time"
)

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() *MyError {
    return &MyError{
        time.Now(), "it didn't work",
    }
}

func main() {
    if err := run(); err != nil {
        fmt.Println(err)
    }
    err1 := MyError{time.Now(), "it works again"}
    fmt.Println(err1)
    fmt.Println(err1.Error())
}

The output of this piece of code is:

at 2015-04-06 15:00:07.1541719 +0800 CST, it didn't work
{2015-04-06 15:00:07.155172 +0800 CST it works again}
at 2015-04-06 15:00:07.155172 +0800 CST, it works again

The thing confused me is under what condition the fmt will implicitly call MyError.Error() interface.

To my understanding, the first and second fmt.Println() should have the same variable type: MyError. But obviously the first call involved an implicit call of Error() of the MyError type, while the second did not.

What mechanism made this difference?

Thanks for looking into this beginner's question!

  • 写回答

2条回答 默认 最新

  • doutinghou6980 2015-04-06 07:34
    关注

    Your code binds the Error() implementation to a pointer *MyError.

    In your code you are passing the type (a copy thereof to be precise) rather than a pointer.

    If you change

    err1 := MyError{time.Now(), "it works again"}
    

    to

    err1 := &MyError{time.Now(), "it works again"}
    

    it will work as you expect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等