Go panics when writing to a nil map

I am learning Go and I ran into the following error when trying to convert a string to a map:

package main
const alphabetStr string = "abcdefghijklmnopqrstuvwxyz"
func main() {
var alphabetMap map[string]bool
  for _, r := range alphabetStr {
c := string(r)
alphabetMap[c] = true
}
}

Running this program throws the following error:

panic: assignment to entry in nil map

I figured this had to do something with the fact that alphabetMap was not declared to be a certain size.

It turns out that I should have been using make to generate my map:

package main
import "fmt"
const alphabetStr string = "abcdefghijklmnopqrstuvwxyz"
func main() {
alphabetMap := make(map[string]bool)
  for _, r := range alphabetStr {
c := string(r)
alphabetMap[c] = true
}
  fmt.Println(alphabetMap["x"])
alphabetMap["x"] = false
fmt.Println(alphabetMap["x"])
}

Running go run main.go should display this output:

before changing value: true
after changing value: false

The reason make is required to generate a map in this context is that a map declared like var alphabetMap map[string]bool will not point to anything in memory, so there is nothing to write to. When trying to write to the nil map, like I did in the first example: alphabetMap[c] = true, will result in a “runtime panic”. An explanation can be found here on the official Go blog, in the section named “Declaration and Initialization”:

Map types are reference types, like pointers or slices, and so the value of m above is nil; it doesn't point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don't do that. To initialize a map, use the built in make function:

So, if you want to declare an “empty” map and then write to it, use make.