douxihui8270 2019-04-29 09:24
浏览 464

如何在Golang中检测结构指针是否为nil?

As is shown by the following code: n := localplugin.NewPluginNet(), the type of n is localnet.Net, which is a interface implemented by the struct pointer *localnet.DomainSocket. Function func NewPluginNet() localnet.Net returns a nil pointer to n.

var n localnet.Net    
n = localplugin.NewPluginNet()
fmt.Println("----> ", n)
if n == nil {
    fmt.Println("n is nil")
}else{
    fmt.Println("n is not nil : ",  n)
}
fmt.Println(reflect.TypeOf(n), reflect.TypeOf(nil), n)

The following is the output of the code above.

---->  <nil>
n is not nil :  <nil>
*localnet.DomainSocket <nil> <nil>

Why does n is not nil ?

===================================

var n1 *localnet.DomainSocket
n1 = nil
fmt.Println(">> ", n1)
if n1 == nil {
    fmt.Println(">>n1 is nil")
}else{
    fmt.Println(">>n1 is not nil : ",  n)
}
fmt.Println(reflect.TypeOf(n1), reflect.TypeOf(nil), n1)

However, it's correct for this case:

>>  <nil>
>>n1 is nil
*localnet.DomainSocket <nil> <nil>
  • 写回答

1条回答 默认 最新

  • dou72260 2019-04-29 09:31
    关注

    Why isn't n nil? Type of n is an interface type (localnet.Net) which is a wrapper for a (type; value) pair. The interface value may be non-nil even if it wraps a nil value. See Hiding nil values, understanding why golang fails here

    To answer the question in title: you may use reflection to tell if a non-nil interface value wraps a nil value (e.g. nil pointer):

    reflect.ValueOf(someValue).IsNil()
    

    Example:

    type reader struct{}
    
    func (*reader) Read(p []byte) (int, error) { return 0, nil }
    
    func main() {
        var r io.Reader = (*reader)(nil)
    
        fmt.Println(r, r == nil)
        fmt.Println(reflect.ValueOf(r).IsNil())
    }
    

    Output (try it on the Go Playground):

    <nil> false
    true
    
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?