如何将 nil 接口转换为 nil 其他接口

我有一个经典的 Go nil 接口问题。

我试图断言 an interface{},我从 a 分配nil error回一个error接口。这句话很令人困惑,所以我有一个方便的例子: 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.

}

输出:


<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

换句话说,我正在尝试从 anil interface{}向下转换为 anil error接口。如果我知道一开始就interface{}被分配为 a ,有没有一种优雅的方法可以做到这一点?nil error


仅供参考,如果这看起来不寻常,那是因为我正在实施一些模拟测试。


aluckdog
浏览 103回答 1
1回答

30秒到达战场

这有效吗?func&nbsp;preferredWay(i&nbsp;interface{})&nbsp;error&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;k,&nbsp;_&nbsp;:=&nbsp;i.(error)&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;k }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go