Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Go does not panic when trying to read from a nil map?

Tags:

go

Here is the code, I expect it will panic when visiting mp["12"], but 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
    }
}
like image 743
sion Avatar asked Oct 15 '25 16:10

sion


1 Answers

You can read from a nil map, but cannot write to it. The language spec says:

A nil map is equivalent to an empty map except that no elements may be added.

like image 181
Burak Serdar Avatar answered Oct 18 '25 11:10

Burak Serdar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!