社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
type interfaceA interface {
Num() int
}
type structA struct {
num int
}
func (s *structA) Num() int {
return s.num
}
func getData(ia interfaceA) {
if ia == nil {
fmt.Println("true")
} else {
fmt.Println("false")
}
}
// 打印结果:true
func TestInitStructIsNil2(t *testing.T) {
var initStruct *structA
if initStruct == nil {
fmt.Println("true")
} else {
fmt.Println("false")
}
}
// 打印结果:false
func TestInitStructIsNil(t *testing.T) {
var initStruct *structA
getData(initStruct)
}
// 打印结果:true
func TestInitInterfaceIsNil(t *testing.T) {
var initInterface interfaceA
getData(initInterface)
}
结果
声明一个结构体A,此时A等于nil
声明一个结构体A,然后将A作为参数传入另一个函数B,函数B接收到的A不为nil
声明一个接口C,然后将C作为参数传给另一个函数B,函数B接收到的C为nil
通过DEBUG发现,当函数B的参数为接口,而传参为结构体时,参数会判断实现接口的结构体的type。此时函数B获取到的参数不等于nil。
查找资料了解到interface{} 有两个属性,type和value。在上一种情况中,type是有值的,所以不等于nil
参考博客https://blog.csdn.net/qq_26981997/article/details/52608081
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!