drn5375 2015-05-11 07:51
浏览 89
已采纳

将nil接口转换为Golang中某物的指针?

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

  • doubi8965 2015-05-11 08:02
    关注

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

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏