assignment to entry in nil map

Go Programming Language

Severity: Moderate

What it means

The full message: panic: assignment to entry in nil map, followed by the stack trace.
The Go spec: a nil map is equivalent to an empty map, except that no elements may be added. Reading from it works. Writing to it panics.
A map declared with var m map[string]int, or a map field in a struct, stays nil until something makes it.

Affected Models

  • Go programs at run time

How to Fix It

  1. Find the first line of your own code in the stack trace, and the map written on it.

  2. Make the map before the first write: m := make(map[string]int), or a literal, m := map[string]int{}. Effective Go: to initialize a map, use the built-in make function.

  3. A map inside a struct? The struct's zero value holds a nil map. Make it where the struct is created, such as in a New function, or before the write: if t.items == nil { t.items = make(map[string]int) }