对于向map,slice这样的类型,如果不对它们进行初始化,它们的零值为nil。在我之前的概念里,对于初始值为nil的变量,如果要对齐进行操作,一定要先进行初始化,如调用make或者new函数。
但是。。。
让我们来看下面的例子:
package main
import (
"fmt"
)
func main() {
var arr []int
fmt.Printf("%T\n", arr)
if arr==nil {
fmt.Println("empty array equals nil")
fmt.Printf("the length is %d\n", len(arr))
}
arr = append(arr, 1, 2) // we operate on this empty varible, and it is ok!!!
}
有以下结论:
- 即使为空值,也能打印出变量的类型;
- 空slice的长度为0;
- 我们可以使用append函数作用在空slice上;
Append函数应该是对于nil值做了判断,因此不需要调用者再外部进行初始化。