V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
BBCCBB
V2EX  ›  程序员

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

  •  1
     
  •   BBCCBB · Oct 20, 2021 · 2382 views
    This topic created in 1663 days ago, the information mentioned may be changed or developed.
    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 呢?

    Supplement 1  ·  Oct 20, 2021
    errorInterface := reflect.TypeOf((*error)(nil)).Elem()

    为啥这里 TypeOf 参数用 error(nil)不行
    Supplement 2  ·  Oct 21, 2021
    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 replies    2021-10-22 09:07:19 +08:00
    silencil
        1
    silencil  
       Oct 20, 2021
    插个楼,问下 Go 的就业前景如何。以及是否卷?
    SingeeKing
        2
    SingeeKing  
    PRO
       Oct 20, 2021
    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  
       Oct 20, 2021
    @silencil 打开 boss 等招聘 app,选择 golang 就知道了
    BBCCBB
        4
    BBCCBB  
    OP
       Oct 20, 2021
    @SingeeKing
    我的问题其实是从下面这行代码来的.
    errorInterface := reflect.TypeOf((*error)(nil)).Elem()

    为啥这里 TypeOf 参数用 error(nil)不行... 🐶
    joesonw
        5
    joesonw  
       Oct 20, 2021 via iPhone
    任意 interface 的 type 都只能这样拿 reflect.Type

    interface 是不能实例化的。但*error 是指针类型。
    BBCCBB
        6
    BBCCBB  
    OP
       Oct 21, 2021
    @joesonw 理是这个理, 但还是懵,哈哈
    BBCCBB
        7
    BBCCBB  
    OP
       Oct 22, 2021
    这样理解也行, struct can not be nil.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5703 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 07:56 · PVG 15:56 · LAX 00:56 · JFK 03:56
    ♥ Do have faith in what you're doing.