dongtangu8403 2014-04-12 15:57
浏览 44
已采纳

当返回类型实际上是错误时,为什么需要返回一个指针?

I am reading the article Error handling and Go, and don't quite understand why a pointer (&errorString{text}) has to be returned when the return type is actually error?

My understanding is error is an interface, and errorString implements the interface, therefore, return errorString is also okay (but it is not the case).

// New returns an error that formats as the given text.
func New(text string) error {
    return &errorString{text}
}

errorString implementation

// errorString is a trivial implementation of error.
type errorString struct {
    s string
}

func (e *errorString) Error() string {
    return e.s
}
  • 写回答

1条回答 默认 最新

  • dongmei9961 2014-04-12 16:00
    关注

    Because error interface for errorString is implemented for a pointer (func (e *errorString) Error()), if it was implemented like below you would return the value directly:

    func (e errorString) Error() string {
        return e.s
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端