Home  >  Article  >  Backend Development  >  Why doesn't Go panic when trying to read a nil map?

Why doesn't Go panic when trying to read a nil map?

WBOY
WBOYforward
2024-02-06 10:00:041091browse

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

Question content

This is the code, I expected a panic when accessing mp["12"] but it fails It works fine there

// 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
    }
}

Correct answer


You can read from a nil map, but not write. The language specification says:

The above is the detailed content of Why doesn't Go panic when trying to read a nil map?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete