加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

指针 – 将Nil接口转换为Golang中某些东西的指针?

发布时间:2020-12-16 19:19:41 所属栏目:大数据 来源:网络整理
导读:在下面的代码片段中,尝试将nil接口转换为某个东西的指针失败,并出现以下错误:interface conversion:interface is nil,not * main.Node type Nexter interface { Next() Nexter}type Node struct { next Nexter}func (n *Node) Next() Nexter {...}func mai
在下面的代码片段中,尝试将nil接口转换为某个东西的指针失败,并出现以下错误:interface conversion:interface is nil,not * main.Node
type Nexter interface {
    Next() Nexter
}

type Node struct {
    next Nexter
}

func (n *Node) Next() Nexter {...}

func main() {
    var p Nexter

    var n *Node
    fmt.Println(n == nil) // will print true
    n = p.(*Node) // will fail
}

播放链接:https://play.golang.org/p/2cgyfUStCI

为什么这会完全失败?这完全有可能

n = (*Node)(nil)

,所以我想知道如何从nil接口开始实现类似的效果.

这是因为静态类型Nexter(它只是一个接口)的变量可能包含许多不同动态类型的值.

是的,因为* Node实现了Nexter,你的p变量可以保存类型为* Node的值,但它也可以包含实现Nexter的其他类型;或者它可能根本没有任何东西(零值).并且Type assertion不能在这里使用,因为引用了规范:

x.(T) asserts that x is not nil and that the value stored in x is of type T.

但在你的情况下,x是零.如果类型断言为假,则会发生运行时混乱.

如果您更改程序以初始化p变量:

var p Nexter = (*Node)(nil)

您的程序将运行并键入断言成功.这是因为接口值实际上以以下形式保持一对:(值,动态类型),在这种情况下,你的p将不是nil,而是将保持一对(nil,* Node);详情见The Laws of Reflection #The representation of an interface.

如果您还想处理接口类型的nil值,可以像这样明确地检查它:

if p != nil {
    n = p.(*Node) // will not fail IF p really contains a value of type *Node
}

或者更好:使用特殊的“逗号 – 确定”形式:

// This will never fail:
if n,ok := p.(*Node); ok {
    fmt.Printf("n=%#vn",n)
}

使用“逗号ok”表单:

The value of ok is true if the assertion holds. Otherwise it is false and the value of n is the zero value for type T. No run-time panic occurs in this case.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读