golang 声明结构体和声明接口的疑点 - Go语言中文社区

golang 声明结构体和声明接口的疑点


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

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_36520153/article/details/87283032
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-02-02 18:42:43
  • 阅读 ( 1139 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢