go:Convert nil interface to pointer of something in Golang

本文探讨了在Golang中从nil接口转换到特定类型指针的问题。通过实例解析了为何直接转换会导致运行时错误,并介绍了如何正确地进行类型断言,包括使用特殊形式的逗号OK断言来避免运行时恐慌。

Convert nil interface to pointer of something in Golang?

Ask Question

up vote 9 down vote favorite

5

In the following code piece, trying to convert a nil interface to a pointer of something fails with the following error: 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
}

Play link here: https://play.golang.org/p/2cgyfUStCI

Why does this fail exactly? It's entirely possible to do

n = (*Node)(nil)

, so I'm wondering how can you achieve a similar effect starting from a nil interface.

pointers interface go

shareimprove this question

edited Aug 3 '16 at 10:21

user6169399

asked May 11 '15 at 7:51

Mihnea Giurgea

137115

add a comment

1 Answer

active oldest votes

up vote 23 down vote accepted

This is because a variable of static type Nexter (which is just an interface) may hold values of many different dynamic types.

Yes, since *Node implements Nexter, your p variable may hold a value of type *Node, but it may hold other types as well which implement Nexter; or it may hold nothing at all (nil value). And Type assertion cannot be used here because quoting from the spec:

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

But x in your case is nil. And if the type assertion is false, a run-time panic occurs.

If you change your program to initialize your p variable with:

var p Nexter = (*Node)(nil)

Your program will run and type assertion succeeds. This is because an interface value actually holds a pair in the form of: (value, dynamic type), and in this case your p will not be nil, but will hold a pair of (nil, *Node); for details see The Laws of Reflection #The representation of an interface.

If you also want to handle nil values of interface types, you may check it explicitly like this:

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

Or better: use the special "comma-ok" form:

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

Using the "comma-ok" form:

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值