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.

Got the actual stack trace?

Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.

Explain my error

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