TryBugHunt

panic: assignment to entry in nil map

panic: assignment to entry in nil map in Go means you attempted to write to a Go map that was declared as a nil map rather than initialized. Reading from a nil map is safe and returns zero values, but writing to it panics immediately.

GoPattern: Null and undefined errors

How do I fix panic: assignment to entry in nil map?

To fix panic: assignment to entry in nil map in Go, locate the line causing the error and check the values right before it runs. Most occurrences happen because of declaring with var without make(). Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.

1. Inspect bounds & typesPrint or inspect collection sizes and verify variables are not empty or None/undefined.
2. Guard with safe accessUse optional chaining (?.), dictionary get(), or guard conditions before dereferencing.
3. Trace upstream originsFind where the value was instantiated or returned rather than only patching the symptom.

What does panic: assignment to entry in nil map mean?

In Go, declaring 'var m map[string]int' leaves m as nil. Unlike Python dicts or JavaScript objects, a nil Go map cannot allocate new entries dynamically. You must allocate the underlying hash table using make(map[string]int) or a map literal before assigning keys.

Why does panic: assignment to entry in nil map happen?

1. Declaring with var without make()

A var declaration creates a nil map pointer without allocating the underlying hash table.

Breaks

var cache map[string]int
cache["hits"] = 1  // panics!

Works

cache := make(map[string]int)
cache["hits"] = 1

2. Uninitialized map field in a struct

Creating a struct with zero-values leaves any map fields set to nil.

Breaks

type User struct {
    settings map[string]string
}
u := User{}
u.settings["theme"] = "dark"

Works

u := User{
    settings: make(map[string]string),
}
u.settings["theme"] = "dark"

How to find it in your own code

Always initialize maps with make(map[K]V) or a map literal map[K]V{} before assigning keys. Use 'if m == nil { m = make(...) }' if the map is initialized lazily.

Try it: fix this bug

easy

panic: assignment to entry in nil map

package main

import "fmt"

func validateUserMap(key string, val string) []string {
	var userSettings map[string]string
	userSettings[key] = val
	return []string{fmt.Sprintf("%s:%s", key, userSettings[key])}
}

func main() {
	fmt.Println(validateUserMap("theme", "dark"))
}
Open with hintsRuns in your browser. No account needed.

More challenges with this error

Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser — no install, no account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.