如何将nil接口转换为nil其他接口 [英] How to cast nil interface to nil other interface

查看:210
本文介绍了如何将nil接口转换为nil其他接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a classic Go nil interface issue.

我试图声明一个interface{},我将它从nil error分配回一个error接口.该句子令人困惑,因此我有一个方便的示例: https://play.golang.com/p/Qhv7197oIE_z

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.
}

输出:

<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

因此,换句话说,我正在尝试从nil interface{}向下转换为nil error接口.如果我知道interface{}首先被指定为nil error,是否有一种优雅的方法?

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.

推荐答案

这项工作有效吗?

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

这篇关于如何将nil接口转换为nil其他接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆