53

golang when is nil not nil

 4 years ago
source link: https://www.tuicool.com/articles/QzU3qeF
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在开发中,我们经常会遇到一个nil值不等于nil,先看一下下面这个例子

type itest struct {
    a string
}

func printA() *itest{
    return nil
}

func main() {
    var i interface{} = printA()
    fmt.Printf("i is nil %v, i = %v", i == nil, i)
}

最后输出结果是 i is nil false, i = <nil>

这是因为interface是由两个元素type:T 和value: V所表示。V是具体值,比如int, struct, pointer的具体值。var i interface = 3, i的type是int, value是3。

只有当type和value都没有设置(T=nil, V 没有赋值)时interface才等于nil。可是在上面例子,i的type是*itest,所以i不是nil。具体解释可以参考 官方FAQ

解决办法:

func main() {
    var i = printA()
    fmt.Printf("i is nil %v, i = %v", i == nil, i)
}

最后输出结果是 i is nil true, i = <nil>

不将i转换成interface类型,i这个时候是*itest类型对应的nil值。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK