Skip to Content
Skip to content
Fix "assignment to entry in nil map" in Go
Beginner
Tutorials

Fix "assignment to entry in nil map" in Go

Reproduce Go's nil map panic, initialize maps with make or literals, and guard struct map fields safely. After this, map writes never crash on zero-value structs.

Updated 6 min read GoTesting and Debugging

Skip ahead: If you already know why var m map[string]int panics and only need struct, function-argument, or nested-map fixes, jump to "Case 2: struct map fields and the value-receiver trap".

Go lets you read from a nil map without complaining, then crashes with panic: assignment to entry in nil map the moment you try to write a key. That half-working behaviour catches beginners out—not just on local variables, but inside zero-valued structs, helper functions, and nested maps. Verified on golang:trixie (Go 1.27.4).

Case 1: the zero-value trap (reading works, writing panics)

This program reads counts["hits"] and len(counts) cleanly, then panics on line 8 when it writes a key:

package main

import "fmt"

func main() {
	var counts map[string]int
	fmt.Println("read missing:", counts["hits"], "len:", len(counts))
	counts["hits"] = 1
}
read missing: 0 len: 0
panic: assignment to entry in nil map

goroutine 1 [running]:
main.main()
	/tmp/t1/main.go:8 +0xdf
exit status 2

var counts map[string]int creates a nil map header with no hash table behind it. Reading returns the value type's zero value (0) and len returns 0, so the map looks harmless until the first assignment has nowhere to store the entry.

When you own the variable locally, allocate the hash table upfront:

  • counts := make(map[string]int) when starting empty
  • counts := make(map[string]int, 100) when you know roughly how many keys you will insert (reduces internal bucket resizes)
  • counts := map[string]int{"/health": 1} when seeding known keys immediately

Case 2: struct map fields and the value-receiver trap

If a caller declares var tr Tracker without calling a constructor, its Counts field starts as nil. A lazy guard inside a method fixes it—only if the method uses a pointer receiver (*Tracker). Look at what happens when you accidentally use a value receiver, or try to initialize a nil map inside a helper function:

package main

import "fmt"

type BadTracker struct {
	Counts map[string]int
}

func (t BadTracker) Hit(path string) {
	if t.Counts == nil {
		t.Counts = make(map[string]int)
	}
	t.Counts[path]++
}

func fillMap(m map[string]int) {
	if m == nil {
		m = make(map[string]int)
	}
	m["ok"] = 1
}

func main() {
	var bt BadTracker
	bt.Hit("/home")
	fmt.Println("after value-receiver Hit:", bt.Counts, "isNil:", bt.Counts == nil)

	var m map[string]int
	fillMap(m)
	fmt.Println("after fillMap:", m, "isNil:", m == nil)
}
after value-receiver Hit: map[] isNil: true
after fillMap: map[] isNil: true

Why did both stay nil? Because a map variable in Go is a pointer-sized header passed by value. Inside fillMap and the value-receiver Hit, make(map[string]int) replaced only the local copy of that header; the caller's bt.Counts and m never changed.

Fix it with a pointer receiver (func (t *Tracker) Hit(path string)) or a constructor (NewTracker()):

package main

import "fmt"

type Tracker struct {
	Counts map[string]int
}

func (t *Tracker) Hit(path string) {
	if t.Counts == nil {
		t.Counts = make(map[string]int)
	}
	t.Counts[path]++
}

func main() {
	counts := make(map[string]int)
	counts["/health"] = 1

	var tr Tracker
	tr.Hit("/health")
	tr.Hit("/health")
	fmt.Println("counts:", counts, "tracker:", tr.Counts)
}
counts: map[/health:1] tracker: map[/health:2]

💡 Tip: Once t.Counts is non-nil, t.Counts[path]++ works even when path is not yet in the map—Go reads 0, adds 1, and writes 1.

Case 3: nested maps still leave every inner map nil

Initializing an outer map like hits := make(map[string]map[string]int) allocates only the outer hash table. Every new outer key still yields a nil inner map until you allocate it explicitly:

package main

import "fmt"

func addHit(hits map[string]map[string]int, host, path string) {
	if hits[host] == nil {
		hits[host] = make(map[string]int)
	}
	hits[host][path]++
}

func main() {
	hits := make(map[string]map[string]int)
	addHit(hits, "xtensyon.com", "/tools")
	addHit(hits, "xtensyon.com", "/tools")
	fmt.Println("nested:", hits)
}
nested: map[xtensyon.com:map[/tools:2]]

Notice that here hits itself was already allocated by the caller before calling addHit, so mutating keys inside hits and assigning hits[host] works without needing a pointer to the outer map.

Case 4: concurrent map writes crash even when initialized

Initializing a map avoids the nil map panic, but it does not make the map safe for multiple goroutines. Writing to the same map from two goroutines at once does not just corrupt keys—the Go runtime aborts the entire process with fatal error: concurrent map writes. Guard shared maps with a sync.Mutex (or sync.RWMutex for read-heavy lookups) and run go test -race ./... to catch unsynchronized writes early.

Which initialization to pick

SituationUseWhy
Local variable, emptymake(map[K]V) or map[K]V{}Allocates hash table immediately
Known approximate key countmake(map[K]V, n)Avoids repeated bucket growth
Struct with map fieldsNewX() constructor + pointer-receiver guardSafe even if caller writes var x X
Nested map (map[A]map[B]C)Check if m[a] == nil before m[a][b] = cOuter make leaves every inner map nil
Shared across goroutinessync.Mutex around reads and writesPrevents concurrent map writes crash

Common mistakes

  • Initializing a map with a value receiver: func (t Tracker) Hit(...) allocates on a copy and leaves the caller's field nil.
  • Assuming len(m) == 0 means initialized: both an empty map and a nil map have length 0. Only m == nil tells them apart.
  • Deleting from a nil map vs. writing: delete(m, k) on a nil map is a safe no-op, which can hide an uninitialized map until the first write.
  • Ignoring val, ok := m[k]: when 0 or "" is a valid stored value, reading m[k] alone cannot distinguish a missing key from a stored zero.

What happens if you skip this

Your code passes read-only unit tests because reading a nil map never panics and delete never panics. The first time a production request hits an optional branch or a fresh struct field that writes to the map—often hours or days later—the whole Go process crashes with assignment to entry in nil map.

Related course: Go for Beginners.

About

Reproduce Go's nil map panic, initialize maps with make or literals, and guard struct map fields safely. After this, map writes never crash on zero-value structs.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
6 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.