dpqjvoq9033 2018-08-05 15:33
浏览 45
已采纳

在此示例中,为什么我们返回一个指针而不是一个值?

package main

import "fmt"


type argError struct {
    arg  int
    prob string
}

func (e *argError) Error() string {
    return fmt.Sprintf("%d - %s", e.arg, e.prob)
}

func f2(arg int) (int, error) {
    return -1, &argError{arg, "can't work with it"}
}

func main() {

    _, e := f2(42)
    if ae, ok := e.(*argError); ok {
        fmt.Println(ae.arg)
        fmt.Println(ae.prob)
    }
}

in f2 we have pointer &argError... as return value, but method declared to return error. Why f2 signature is not defined as

func f2(arg int) (int, *error) instead? Or why do we return pointer not a value in this case?

  • 写回答

1条回答 默认 最新

  • dousi6405 2018-08-05 15:45
    关注

    error is an interface that asks to have an Error() string method.

    The problem here is that you declare the Error() string method on a pointer. func (e *argError) Error() string, thus only an *argError implements an error, but not an argError. So you can only return an &argError{...}.

    You should know that *error and error of an pointer is different. The former is a pointer to an interface holding whatever concrete type and the latter is an interface holding a pointer.

    In practice, since an interface is all about methods, a pointer to an interface is rarely useful while an interface holding a pointer is widely used.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败