dongmin4990 2019-09-04 03:20
浏览 53
已采纳

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

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条回答 默认 最新

  • duan1396 2019-09-04 03:25
    关注

    Does this work?

    func preferredWay(i interface{}) error {
        k, _ := i.(error)
        return k
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型