简单概括:
当你定义一个变量时,会默认赋予这个变量零值.
值类型:0,"",false
引用类型:nil(func,interface,slice,map,channel,指针)
结构体会遍历内部成员,分别赋予零值.
注意点:
1. 注意声明和初始化的区别
var a []int 未初始化,是nil
a:=[]int{} 初始化了,不是nil
2.如果对象是nil,可以调用它的方法
对象是nil,调用方法没问题,赋值时才有问题
3.结构体定义的区别
type student struct {
age int
class []string
}
func (s *student) speak() {
fmt.Println("hahaha")
}
func (s *student) getAge() int {
return s.age
}
func (s *student) setAge() {
s.age = 18
}
func (s *student) getClass() []string {
return s.class
}
func (s *student) setClass() {
s.class = []string{"math", "chinese"}
}
case1:
var a student fmt.Println(a==nil) //cannot convert 'nil' to type 'student'
a的age和class有默认零值
case2:
var a student fmt.Println(a.getAge())
没错,打印的是0
case3:
var a *student fmt.Println(a==nil) fmt.Println(a.getAge())
a这里是指针类型,因此可以和nil比较.结果是 true
获取a的age字段,因为a都是空的.没有分配内存,你调用肯定是空指针
case4:
var a *student a.speak()
打印 "hahah" 虽然是nil,但是还是可以调用
case5:
var a = new(student) a.getAge()
知识点: new的定义 func new(Type) *Type 传入类型,返回类型指针.其值为类型的零值
其实相当于
a:=&student{}