duandu2980 2019-01-23 03:52
浏览 108
已采纳

为什么Golang自定义错误变量具有多种类型

i'm a new gopher and got really confused by variable types, if i'm defining a custom error

    import (
        "fmt"
        "reflect"
    )

    // custom errors
    type myError struct {
        msg string
    }

    func (m *myError) Error() string {
        return m.msg
    }

    func errorGen() error {
        return &myError{"custom error"}
    }

generate a new error and check the type of it

    func main() {
        e := errorGen()
        fmt.Println(reflect.TypeOf(e).Kind()) // type = pointer

        // first type assertion
        _, ok := e.(error)
        if ok {
            fmt.Println("type assertion error") // type = error
        }

        // second type assertion
        _, ok = e.(*myError)
        if ok {
            fmt.Println("type assertion *myError") // type = pointer
        }
    }

so in above code variable 'e' shows 2 types at the same time. What exactly is e's type? and why "error" is an interface and also can be used as return type?

thank you very much

  • 写回答

2条回答 默认 最新

  • donglie1898 2019-01-23 06:36
    关注

    You have to differentiate between the "static type" and the "dynamic type" of a variable.

    Each and every variable in Go has exactly one static type. Some example:

    • After declaring a := 5 the static type of a is int and that is all to know about a.
    • The static type of e in your code is error(because that is what errorGen returns).
    • You can be explicit about the static type like this: var b uint16 = 9.

    Now there are interface types in Go. error is such an interface type, see Peter's answer. Some variables will have error as their static type; your e is an example. Now, the whole purpose of a variable of interface type is to store values of various types which implement this interface. So a interface variable which is not nil somehow "contains" an other variable (actually a value). The type of this contained value can be any one which implements the interface. The type of the contained value is the "dynamic type". Type assertion let you extract values of this dynamic type.

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

报告相同问题?

悬赏问题

  • ¥15 matlab提取运动物体的坐标
  • ¥15 人大金仓下载,有人知道怎么解决吗
  • ¥15 一个小问题,本人刚入门,哪位可以help
  • ¥15 python安卓开发
  • ¥15 使用R语言GD包一直不出结果
  • ¥15 计算机微处理器与接口技术相关问题,求解答图片的这个问题,有多少个端口,端口地址和解答问题的方法和思路,不要AI作答
  • ¥15 如何根据一个截图编写对应的HTML代码
  • ¥15 stm32标准库的PID角度环
  • ¥15 ADS已经下载好了,但是DAS下载不了,一直显示这两种情况,有什么办法吗,非常急!
  • ¥100 Excel 点击发送自动跳转outlook邮件