I’ve been a bit confused for a while over when a map in Golang gets created with a value of nil
(its zero value) and when it does not, so I’m writing this to help me remember.
Let’s look at various ways to initialize a map:
package main
import "fmt"
func main() {
m1 := map[string]string{} // initializes map
m2 := make(map[string]string) // also initializes map
var m3 map[string]string // does NOT initialize the map! HERE BE DRAGONS!
fmt.Println(m1 == nil) // false
fmt.Println(m2 == nil) // false
fmt.Println(m3 == nil) // true
m1["foo"] = "bar"
m2["foo"] = "bar"
m3["foo"] = "bar" // panics because the map is NOT initialized, i.e., map is still nil
}
My takeaways from this are:
- I should (always?) initialize map variables.
map[string]string{}
andmake(map[string]string)
are equivalent unless you need to either (a) give your map some values when creating it or (b) set the size of the map.
Further reading: Which is the nicer way to initialize a map?