這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
本文是Francesc Campoy在GoConf上做的Understanding Nil演講的筆記。
(1)nil沒有type。
(2)在Go語言中,未顯示初始化的變數擁有其類型的zero value。共有6種類型變數的zero value是nil:pointer,slice,map,channel,function和interface。具體含義如下:
| 類型 |
nil值含義 |
| pointer |
指向nothing |
| slice |
slice變數中的3個成員值:buf為nil(沒有backing array),len和cap都是0 |
| map,channel,function |
一個nil pointer,指向nothing |
| interface |
interface包含”type, value”,一個nil interface必須二者都為nil:”nil, nil” |
對於interface來說,正因為需要<type, value>這個元組中兩個值都為nil,interface值才是nil。所以需要注意下面兩點:
a)Do not declare concrete error vars:
func do() error { var err *doError // nil of type *doError return err // error (*doError, nil)}func main() { err := do() // error (*doError, nil) fmt.Println(err == nil) // false}
b)Do not return concrete error types:
func do() *doError { return nil // nil of type *doError}func main() { err := do() // nil of type *doError fmt.Println(err == nil) // true}func do() *doError { return nil // nil of type *doError}func wrapDo() error { // error (*doError, nil) return do() // nil of type *doError}func main() { err := wrapDo() // error (*doError, nil) fmt.Println(err == nil) // false}
(3)nil一些有用的使用情境:
| 類型 |
nil值使用情境 |
| pointer |
methods can be called on nil receivers |
| slice |
perfectly valid zero values |
| map |
perfect as read-only values(往nil map新增成員會導致panic) |
| channel |
essential for some concurrency patterns |
| function |
needed for completeness |
| interface |
the most used signal in Go (err != nil) |