Go語言中的nil

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

本文是Francesc Campoy在GoConf上做的Understanding Nil演講的筆記。

(1)nil沒有type

(2)在Go語言中,未顯示初始化的變數擁有其類型的zero value。共有6種類型變數的zero valuenilpointerslicemapchannelfunctioninterface。具體含義如下:

類型 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>這個元組中兩個值都為nilinterface值才是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)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.