英文:
Convert nil interface to pointer of something in Golang?
问题
在上面的代码片段中,尝试将一个空接口转换为某个指针会导致以下错误:interface conversion: interface is nil, not *main.Node。
为什么会出错呢?实际上,可以通过以下方式实现类似的效果:
n = (*Node)(nil)
但是,从空接口开始,如何实现类似的效果呢?这是因为空接口的值为nil,它不包含任何具体的类型信息。因此,无法将空接口直接转换为指针类型。在这种情况下,你可以使用类型断言来判断接口的动态类型是否为nil,然后再进行转换。例如:
if p == nil {
    n = nil
} else {
    n = p.(*Node)
}
这样,如果接口p的动态类型为nil,则将n赋值为nil;否则,将p转换为*Node类型并赋值给n。
希望对你有所帮助!
英文:
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.
答案1
得分: 50
这是因为一个类型为_static_的变量Nexter(只是一个接口)可以保存许多不同的_dynamic_类型的值。
是的,由于*Node实现了Nexter接口,你的变量p可能保存了*Node类型的值,但它也可能保存其他实现了Nexter接口的类型,或者根本不保存任何值(nil值)。而且类型断言在这里不能使用,因为根据规范的引用:
> x.(T) 断言 x 不是 nil,并且 x 中存储的值的类型是 T。
但在你的情况下,x 是 nil。如果类型断言为假,会发生运行时恐慌。
如果你将程序更改为使用以下方式初始化变量 p:
var p Nexter = (*Node)(nil)
你的程序将运行,并且类型断言成功。这是因为接口值实际上以 (value, dynamic type) 的形式保存了一对值,而在这种情况下,p 不会是 nil,而是保存了一对 (nil, *Node);有关详细信息,请参阅反射定律 #接口的表示。
如果你还想处理接口类型的 nil 值,可以像这样显式检查:
if p != nil {
    n = p.(*Node) // 如果 p 真的包含了 *Node 类型的值,这里不会失败
}
或者更好地使用特殊的“逗号-OK”形式:
// 这永远不会失败:
if n, ok := p.(*Node); ok {
	fmt.Printf("n=%#v\n", n)
}
使用“逗号-OK”形式:
> 如果断言成立,ok 的值为 true。否则,它为 false,而 n 的值是类型 T 的零值。在这种情况下不会发生运行时恐慌。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论