How to cast nil interface to nil other interface

蓝咒 提交于 2020-05-30 09:36:52

问题


I have a classic Go nil interface issue.

I'm trying to assert an interface{}, which I assign from a nil error, back to an error interface. That sentence is confusing so I have a handy-dandy example: https://play.golang.com/p/Qhv7197oIE_z

package main

import (
    "fmt"
)

func preferredWay(i interface{}) error {
    return i.(error)
}

func workAround(i interface{}) error {
    if i == nil {
        return nil
    }
    return i.(error)
}

func main() {
    var nilErr error
    fmt.Println(workAround(nilErr))    // Prints "<nil>" as expected.
    fmt.Println(preferredWay(nilErr))  // Panics.
}

Output:

<nil>
panic: interface conversion: interface is nil, not error

goroutine 1 [running]:
main.preferredWay(...)
    /tmp/sandbox415300914/prog.go:8
main.main()
    /tmp/sandbox415300914/prog.go:21 +0xa0

So in other words, I'm trying to downcast from a nil interface{} to a nil error interface. Is there an elegant way to do this if I know the interface{} was assigned as a nil error to begin with?

FYI, if this seems unusual, it's because I'm implementing some mocking for testing.


回答1:


Does this work?

func preferredWay(i interface{}) error {
    k, _ := i.(error)
    return k
}


来源:https://stackoverflow.com/questions/57781058/how-to-cast-nil-interface-to-nil-other-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!