go runtime_error ai_generated true

panic: assignment to entry in nil map

ID: go/assignment-to-entry-in-nil-map

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Writing to an uninitialized map. Maps must be created with make() before use.

generic

Workarounds

  1. 98% success Initialize with make(): m := make(map[string]int)
    m := make(map[string]int)

    Sources: https://go.dev/blog/maps

  2. 95% success Or use map literal: m := map[string]int{}
    m := map[string]int{}

    Sources: https://go.dev/blog/maps

  3. 90% success For struct fields, initialize in constructor or init function
    func NewFoo() *Foo {
        return &Foo{data: make(map[string]int)}
    }

    Sources: https://go.dev/blog/maps

Dead Ends

Common approaches that don't work:

  1. Check for nil before every map write 70% fail

    Verbose and error-prone — just initialize the map

  2. Use sync.Map for all maps 65% fail

    sync.Map is for concurrent access — overkill for single-goroutine use

Error Chain

Frequently confused with: