Assignment to Entry in Nil Map

assignment to entry in nil map

Quick Answer

You are writing to a map that was declared but never initialized with make(). Initialize the map before assigning values.

Why This Happens

In Go, declaring a map variable with var m map[string]int gives you a nil map. Reading from a nil map returns the zero value, but writing to it causes a panic. You must initialize it with make() or a map literal before use.

The Problem

func main() {
    var m map[string]int
    m["count"] = 1 // panic: assignment to entry in nil map
}

The Fix

func main() {
    m := make(map[string]int)
    m["count"] = 1 // works fine
}

Step-by-Step Fix

  1. 1

    Identify the nil map

    Find the map variable in the panic stack trace and check how it was declared.

  2. 2

    Trace the declaration

    Look for var declarations or struct fields of map type that are never initialized.

  3. 3

    Initialize with make

    Use make(map[K]V) or a map literal to initialize the map before writing to it.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free