這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
原文:https://golang.org/ref/spec#The_zero_value
The 零值
當一個變數或者新值被建立時, 如果沒有為其明確指定初始值,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 intvar i int = 0
After
type T struct { i int; f float64; next *T }t := new(T) //A
the following holds: //C
t.i == 0t.f == 0.0t.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.
注意: 此文章只是我個人筆記, 如有錯漏,請一定指正, 共同學習, 我的郵箱: htyu_0203_39@sina.com