golang 一个nil传入方法中后就变成not nil? 这是为什么?

package main
    
import "fmt"

type Hello struct{
    Values string
}

func main () {
    var hi []*Hello
    fmt.Println(hi)
    if hi == nil {
        fmt.Println("the value is nil")
    }
    
    Console(hi)
}

func Console(data interface{}) {
    if(data == nil){
        fmt.Println("is nil")
    }else{
        fmt.Println("not nil")
    }
}

打印出来是

[]
the value is nil
not nil

1.为什么Console里面打印出来的是 not nil?
2.如何实现Console里面可以打印出nil?(需要一个通用的方法所以才用了interface{})

阅读 2.5k
2 个回答

接口 interface ,包括两方面

  • type 接口类型
  • value 接口动态值

判断 data interface{} == nil,要同时满足这两个方面。
在你的例子中, type 是有值的,value == nil

这就对应了 reflect.TypeOfreflect.ValueOf 两个方法

除了反射还有其他办法吗?

func Console(data interface{}) {
    v := reflect.ValueOf(data)
    if(v.IsNil()){
        fmt.Println("is nil")
    }else{
        fmt.Println("not nil")
    }
}
推荐问题