V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
BBCCBB
V2EX  ›  程序员

Golang 中 error(nil) 为啥 type 也是 unset?

  •  1
     
  •   BBCCBB · 2021-10-20 16:54:04 +08:00 · 1804 次点击
    这是一个创建于 890 天前的主题,其中的信息可能已经有所发展或是发生改变。
    m := error(nil)
    n := (*error)(nil)
    fmt.Printf("%T %+v \n", m, m)
    fmt.Printf("%T %+v \n", n, n)
    
    

    得到的结果

    <nil> <nil>
    *error <nil>

    为啥 m 的 type 是 unset 呢?

    第 1 条附言  ·  2021-10-20 23:07:02 +08:00
    errorInterface := reflect.TypeOf((*error)(nil)).Elem()

    为啥这里 TypeOf 参数用 error(nil)不行
    第 2 条附言  ·  2021-10-21 14:18:42 +08:00
    https://github.com/golang/go/issues/35427

    From the doc of reflect.TypeOf:

    > TypeOf returns the reflection Type that represents the dynamic type of i. If i is a nil interface value, TypeOf returns nil.

    io.Reader(nil) is a nil interface value. Castingnil to an interface type is still nil.

    See the example for reflect.TypeOf. You want to instead do:

    reflect.TypeOf((*io.Reader)(nil)).Elem()

    Casting a nil pointer to an interface type is not nil.
    7 条回复    2021-10-22 09:07:19 +08:00
    silencil
        1
    silencil  
       2021-10-20 16:58:17 +08:00
    插个楼,问下 Go 的就业前景如何。以及是否卷?
    SingeeKing
        2
    SingeeKing  
       2021-10-20 17:06:20 +08:00
    error 是接口,%T 打印的是实际类型而不是接口类型,下面的程序 type 就有值了

    type Error struct {}
    func (e Error) Error() string { return "error" }

    var p error = (*Error)(nil)
    fmt.Printf("%T %+v \n", p, p)
    lipd
        3
    lipd  
       2021-10-20 18:06:20 +08:00
    @silencil 打开 boss 等招聘 app,选择 golang 就知道了
    BBCCBB
        4
    BBCCBB  
    OP
       2021-10-20 23:06:46 +08:00
    @SingeeKing
    我的问题其实是从下面这行代码来的.
    errorInterface := reflect.TypeOf((*error)(nil)).Elem()

    为啥这里 TypeOf 参数用 error(nil)不行... 🐶
    joesonw
        5
    joesonw  
       2021-10-20 23:51:43 +08:00 via iPhone
    任意 interface 的 type 都只能这样拿 reflect.Type

    interface 是不能实例化的。但*error 是指针类型。
    BBCCBB
        6
    BBCCBB  
    OP
       2021-10-21 09:03:35 +08:00
    @joesonw 理是这个理, 但还是懵,哈哈
    BBCCBB
        7
    BBCCBB  
    OP
       2021-10-22 09:07:19 +08:00
    这样理解也行, struct can not be nil.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   933 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:59 · PVG 04:59 · LAX 13:59 · JFK 16:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.