原文:https://golang.org/ref/spec#The_zero_value
当一个变量或者新值被创建时, 如果没有为其明确指定初始值,go语言会自动初始化其值为此类型对应的零值, 各类型零值如下:
false : bool, 0: integer, 0.0: float, "": string, nil : pointer, function, interface, slice, channel, map 。对于复合类型, go语言会自动递归地将每一个元素初始化为其类型对应的零值。
比如:数组, 结构体 。
原文:
When storage is allocated for a variable, either through a declaration or a call of new
, or when a new value is created, either through a composite literal or a call of make
, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type:false
for booleans, 0
for integers, 0.0
for floats, ""
for strings, and nil
for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.
These two simple declarations are equivalent(以下两处声明是等价的):
var i int
var i int = 0
After
type T struct { i int; f float64; next *T }
t := new(T) //A
the following holds: //C
t.i == 0
t.f == 0.0
t.next == nil
The same would also be true after(注意:A与B两种变量创建方式,但是其每一个元素都被go自动初始化其类型对应零值, 等同于C)
var t T //B
nil 是专门为go语言的指针类型和引用类型准备的,这样好记,哈哈;最后提醒一句:go语言的数组和结构体可是值类型, 并非引用类型哟, 比如数组作为函数参数时,
因为是值类型, 所以要复制的哟, 如果数组中元素很多, 那复制代价就大了呢, 要注意呀!
注意: 我是C++菜鸟程序员, 一毕业入行就用C++多年, 能力不见得强, 但是养成了刨根的毛病, 程序写的好不好, 大面的东西大家都差不多,但对于这些细节的东西
往往不注意, 隐藏bug就多, go语言虽然以简洁易学强大得名,但是还是要细节上多注意, 以免掉坑。 好比C++指针零值:0, NULL, nullptr 就是其零值不统一,很容易出bug.