首頁  >  文章  >  後端開發  >  為什麼 Go 在嘗試讀取 nil 映射時不會恐慌?

為什麼 Go 在嘗試讀取 nil 映射時不會恐慌?

WBOY
WBOY轉載
2024-02-06 10:00:041094瀏覽

为什么 Go 在尝试读取 nil 映射时不会恐慌?

問題內容

這是程式碼,我預期造訪mp["12"] 時會出現恐慌,但它在那裡工作正常

// You can edit this code!
// Click here and start typing.
package main

import "log"

func main() {
    var mp map[string]int = nil
    log.Println(mp["12"], "12") // works fine
    if mp == nil {
        panic("map is nil") // panic here
    }
}

正確答案


您可以從 nil 映射中讀取,但無法寫入。語言規範說:

以上是為什麼 Go 在嘗試讀取 nil 映射時不會恐慌?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除