Fix Go "assignment to entry in nil map" Panic — Declared Maps, Struct Fields, and Nested Maps
A map in Go has two separate lives: the declaration that gives a variable a map type, and the allocation that gives it somewhere to put entries. Code that has only the first still compiles, still reads as if the map were empty, and still answers lookups with zero values — and then panics on the first assignment, at whatever line happens to run first in production. Each section below takes one shape that leaves a map nil, shows the exact panic it prints, and gives the initialization that belongs to that shape.
Written November 20, 2026 · Tested with Go 1.26.4 · 21 min read
- The first panic: a map declared with var and never made
- Reading the message: a panic, a trace, and no map name
- Why the reads pass: a nil map reads exactly like an empty map
- The struct field: a zero-value struct carries a nil map
What this guide is
panic: assignment to entry in nil map is a run-time failure, not a compile error. The program builds cleanly, because nothing about assigning to a map is wrong in the source: the key type fits, the value type fits, the syntax is ordinary. What is wrong is a fact about the value the map variable holds when the assignment runs. A map that has been declared but never allocated holds nil — the specification states it directly: the value of an uninitialized map is nil — and a nil map has no storage behind it. The specification's map rules draw the line exactly where the runtime does: a nil map is equivalent to an empty map except that no elements may be added, and assigning to an element of a nil map causes a run-time panic. Reads are not the problem, and this guide spends a full section on them, because the reads are why the defect survives: a nil map answers every lookup, length check, and range loop exactly as an empty map would, so the code looks correct right up to the first write.
The fix is never a change to the assignment. The assignment is where the panic is reported, not where the defect is. The defect is upstream, at the place the map should have been allocated and was not — with make, with a composite literal, or with a guard at the first write for a map that arrives from somewhere else. The sections below are organized by where that missing allocation belongs: at the declaration, in the struct's constructor, before the branch, at the boundary where a returned map is received, and one level down for a map inside a map.
The examples here use Go 1.26.4. Every example lives in a single file named main.go inside one module, created once from an empty directory:
$ mkdir nilmap
$ cd nilmap
$ go mod init example.com/nilmap
go: creating new go.mod: module example.com/nilmap
Each program that follows replaces the contents of that main.go. The panic transcripts are shown as printed by go run -trimpath main.go: the -trimpath flag only changes how file positions print in the trace — ./main.go:7 here, where a plain run prints the same line number behind the full directory path on your machine. Tested with Go 1.26.4.
The first panic: a map declared with var and never made
The smallest program that earns the panic declares a map, assigns to it, and reads the value back:
// main.go
package main
import "fmt"
func main() {
var counts map[string]int
counts["apple"] = 1
fmt.Println(counts["apple"])
}
$ go run -trimpath main.go
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
./main.go:7 +0x2c
exit status 2
The var counts map[string]int line is a complete, legal declaration. It gives counts its type, map[string]int, and its value, which for a map type is nil — not an empty map, but no map at all. The assignment on the next line is the first operation that needs the map to exist, and it is the operation the specification reserves the panic for. Nothing earlier in the program complains, because nothing earlier asks the map to hold anything.
The fix for this shape is to allocate at the declaration, with make:
counts := make(map[string]int)
make is the built-in that creates a new, empty map value of the given type, optionally with a capacity hint — make(map[string]int, 100) — that sizes the initial storage without bounding how large the map can grow. A composite literal does the same job when the first entries are already known: counts := map[string]int{"apple": 1}. Either form replaces the var line; what does not work is keeping the var line and assigning sooner, or assigning a different way. The variable needs a map behind it before any write, and only an allocation puts one there.
Reading the message: a panic, a trace, and no map name
Three things in the output are worth reading closely, because each one tells you where to look and where not to.
First, this is a panic, so it arrives at run time with a goroutine trace, not at build time with a file position in the compiler's format. go build on the program above succeeds in silence. The failure waits for the assignment line to execute, which means it also waits for whatever input, branch, or call path leads to that line — a program can run for a long time, and pass tests that never reach the write, before the panic appears.
Second, the trace position is the assignment, not the declaration. ./main.go:7 is the counts["apple"] = 1 line, the write that needed storage. The frame names the function that was running, main.main(), and in a larger program the frames above the panic walk back through the calls that reached the write. Read the trace from the top frame down to find the write, then follow the map variable back through the code to find where it was supposed to be made — that second step is the actual debugging, and the panic does not do it for you.
Third, the message names no map. It says "a nil map", not which one. A line that writes to one of several maps — a struct field, a package-level variable, a value from a function call — leaves the identification to the reader: the trace gives the line, and the line gives the map expression being assigned to, and that expression is the one that was nil. The offset at the end of the frame line, +0x2c, is a position inside the compiled function; it changes as the code changes and carries no information the line number does not carry better.
Why the reads pass: a nil map reads exactly like an empty map
The reason this defect reaches production is that every read operation treats a nil map as an empty one. The program below performs the full set of reads on a map that was never made, and every one of them succeeds:
// main.go
package main
import "fmt"
func main() {
var counts map[string]int
fmt.Println(counts["apple"])
value, ok := counts["apple"]
fmt.Println(value, ok)
fmt.Println(len(counts))
for key, value := range counts {
fmt.Println(key, value)
}
delete(counts, "apple")
clear(counts)
fmt.Println("reads finished", counts == nil)
}
$ go run main.go
0
0 false
0
reads finished true
Each line is one of the specification's read rules in action. A lookup for a key that is not present — and in a nil map no key is present — returns the zero value for the element type, so counts["apple"] is 0. The two-value form reports ok as false, which is the correct answer for an absent key in any map. len is 0. Ranging over the map runs zero iterations, so the loop body never prints. delete and clear remove nothing and do not complain. And the final line confirms the state the whole program ran in: counts == nil is true. The map was nil the entire time, and no read could tell.
This asymmetry is the whole trap. A test that only reads — that checks a lookup returns zero, or that a missing key reports ok false — passes against a nil map and against a made empty map identically. The two states differ only at the first write, so only a test that writes can catch the missing allocation, and the write is often the operation the test was written to avoid disturbing. When a panic like this appears, the question to ask of the code is never "where is the bad assignment" but "which path let this map reach a write without passing through an allocation" — and the shapes below are the paths that do it.
The struct field: a zero-value struct carries a nil map
A map field inside a struct is nil in the struct's zero value, and a struct literal that does not mention the field leaves it there:
// main.go
package main
import "fmt"
type Counter struct {
counts map[string]int
}
func main() {
c := Counter{}
c.counts["apple"]++
fmt.Println(c.counts["apple"])
}
$ go run -trimpath main.go
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
./main.go:11 +0x2c
exit status 2
c := Counter{} is a complete initialization of everything except the map: the struct exists, the field exists, and the field's value is the zero value for its type, which for a map is nil. The write here is c.counts["apple"]++, and an increment is an assignment — it reads the current value, adds one, and stores the result back into the map — so it needs the same storage a plain assignment does, and panics the same way.
This shape is the one that survives code review, because the declaration site and the write site are in different places and the type looks self-contained: Counter declares its map, so a reader assumes Counter provides it. The fix is to make the struct provide it, at the point the struct is created. A constructor is the reliable form:
func NewCounter() Counter {
return Counter{counts: make(map[string]int)}
}
With the field initialized there, every caller that goes through the constructor gets a writable map, and the zero value of the struct is no longer the way working values are produced. A literal at each call site — Counter{counts: make(map[string]int)} — works for a program this size and stops working as a discipline the moment a second call site forgets it, which is the same failure one level up.
Made on one branch only: the map that works until the other path runs
An allocation inside a conditional covers only the calls that take that branch:
// main.go
package main
import "fmt"
func main() {
warm := false
var counts map[string]int
if warm {
counts = make(map[string]int)
}
counts["apple"] = 1
fmt.Println(counts["apple"])
}
$ go run -trimpath main.go
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
./main.go:11 +0x2c
exit status 2
With warm set to true, this program prints 1 and exits normally — the branch runs, the map is made, the assignment has storage. With warm false, the assignment is the same line, the same key, the same value, and it panics, because the map variable still holds the nil its var declaration gave it. Nothing about the write changed; what changed is which statements ran before it.
This is the shape behind the version of the bug that "only happens in production": the branch that allocates is the common path — the cache-warming path, the path the developer's test data takes — and the branch that skips it is the cold start, the empty input, the first run. The repair is to move the allocation out of the condition: make the map before the branch, and let the branch decide only what goes into it. If the allocation is genuinely expensive and genuinely optional, the guard belongs at the write instead, in the form the fixed program at the end of this guide uses: test the map for nil at the point of first use, and make it there if it is still nil.
The map a function hands back: nil crosses the call boundary
A function that returns a map can return nil, and the caller's assignment then panics in the caller's code, on a map the caller never declared:
// main.go
package main
import "fmt"
func savedCounts(saved bool) map[string]int {
if saved {
return map[string]int{"apple": 3}
}
return nil
}
func main() {
counts := savedCounts(false)
counts["pear"] = 1
fmt.Println(counts)
}
$ go run -trimpath main.go
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
./main.go:14 +0x28
exit status 2
The trace position, line 14, is the assignment in main — correct, and incomplete. The nil was decided inside savedCounts, on the path where saved is false, and return nil for a map result is a legal, ordinary statement: nil is a value of every map type, and a function may return it to mean "there is nothing saved". Change the call to savedCounts(true) and the same assignment prints map[apple:3 pear:1] and runs cleanly, because that path returns a literal with storage behind it. The caller's line is identical in both runs; the difference is entirely in what crossed the call boundary.
Where the fix belongs depends on the contract the function means to offer. If nil is a meaningful answer the caller must handle — "no saved counts exist" is information a caller may need — the caller checks for it before writing, and the guard at the point of use is the fix:
counts := savedCounts(false)
if counts == nil {
counts = make(map[string]int)
}
If nil carries no meaning and every caller will write to the result, the function should return an empty made map on that path instead — return make(map[string]int) — and the contract becomes "the result is always writable". What does not work is splitting the difference: returning nil and having some callers guard and others assume. The panic will arrive at the first caller that assumed, and the trace will point at that caller, not at the return that set it up.
Nested maps: making the outer map does not make the inner ones
A map whose element type is itself a map has two levels of allocation, and make performs one of them:
// main.go
package main
import "fmt"
func main() {
groups := make(map[string]map[string]int)
groups["fruit"]["apple"] = 1
fmt.Println(groups["fruit"]["apple"])
}
$ go run -trimpath main.go
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
./main.go:7 +0xc5
exit status 2
The outer map here is made — make ran, on the line directly above the assignment — and the panic still fires, at the same line as always: the assignment. Reading the expression from the inside out shows why. groups["fruit"] is a lookup on the outer map. The key "fruit" is not present, and a lookup for an absent key returns the zero value for the element type. The element type is map[string]int, whose zero value is nil. So the expression being assigned into is a nil map that the lookup itself just produced, and assigning 1 to its "apple" entry is the same write to a nil map as every other section of this guide.
The fix is to create the inner map before assigning into it, and the standard form checks the lookup result first:
groups := make(map[string]map[string]int)
if groups["fruit"] == nil {
groups["fruit"] = make(map[string]int)
}
groups["fruit"]["apple"] = 1
The comparison against nil is doing real work here: it distinguishes "this group has no map yet" from "this group has a map", and it stays correct on the second and later uses, when the inner map exists and must be kept rather than replaced. Replacing it unconditionally — assigning a fresh make result to groups["fruit"] before every write — would not panic, and would silently discard every entry already stored, which is a worse failure than the panic precisely because nothing reports it.
The contrasts: a nil slice takes appends, and this failure waits for run time
Two contrasts close the rule off. First, slices behave the other way. A slice declared with var and never made is also nil, and appending to it works:
// main.go
package main
import "fmt"
func main() {
var names []string
names = append(names, "apple")
fmt.Println(names, len(names), names == nil)
}
$ go run main.go
[apple] 1 false
The output is [apple] 1 false: append allocated storage, returned a slice holding one element, and the variable is no longer nil afterward. Habits formed on slices — declare with var, let the first use sort it out — transfer to maps as a panic, because append returns a new slice value for the caller to keep, while a map assignment stores into the map value itself and needs that value to exist already. Of the two reference-like types a beginner meets first, the map is the one whose zero value cannot be written to.
Second, the failure is a run-time panic, where most of the errors in this family are compile errors. The compiler checks the assignment's types and finds them correct; it does not track which maps a variable might hold when the line runs, and a map that is nil on one path and made on another is one variable with one type, so there is nothing at the assignment for it to reject. Every defense is therefore in the code's structure — allocations placed where every path passes through them, constructors that return complete values, guards where a map crosses a boundary — and not in any setting or check the toolchain offers. A recover in a deferred call can catch the panic, and catching it converts a missing allocation into a silently skipped write; the entry the caller believes it stored is not in any map. Fix the allocation, not the panic.
The fixed program
One program that applies each fix at once — make at the declaration, a constructor that initializes the struct field, a nil guard where a returned map is received, and a check-and-make for the inner map of a nested map:
// main.go
package main
import "fmt"
type Counter struct {
counts map[string]int
}
func NewCounter() Counter {
return Counter{counts: make(map[string]int)}
}
func savedCounts(saved bool) map[string]int {
if saved {
return map[string]int{"apple": 3}
}
return nil
}
func main() {
counts := make(map[string]int)
counts["apple"] = 1
fmt.Println(counts["apple"])
c := NewCounter()
c.counts["apple"]++
fmt.Println(c.counts["apple"])
loaded := savedCounts(false)
if loaded == nil {
loaded = make(map[string]int)
}
loaded["pear"] = 1
fmt.Println(loaded["pear"], len(loaded))
groups := make(map[string]map[string]int)
if groups["fruit"] == nil {
groups["fruit"] = make(map[string]int)
}
groups["fruit"]["apple"] = 1
fmt.Println(groups["fruit"]["apple"])
}
$ go run main.go
1
1
1 1
1
The output is four lines of 1, each from a different fix. The made map stores and reads back 1. The constructor-built Counter increments its field from the zero value a lookup returns to 1. The received map, nil as returned, is made by the guard and then holds one entry, so the lookup prints 1 and the length prints 1. The nested map's inner level, created by the check-and-make, stores its first entry and reads back 1.
The fixes, ranked
Allocate where the map is declared. make at the declaration, or a composite literal when the first entries are known. This is the fix for the var-declared shape and for any map whose whole life is inside one function. It is the strongest form because no path through the code can reach the variable before the allocation — the allocation is the declaration.
Initialize map fields where the struct is built. A constructor that fills every map field, so the zero value of the struct is never the working value. This is the fix for the struct-field shape, and it holds as call sites multiply in a way that per-site literals do not.
Guard at the first write for a map that arrives from elsewhere. if m == nil { m = make(...) } where a map is received from a function, a parameter, or a decoded value whose contract allows nil. This is the fix for the returned-nil shape and for the conditional-allocation shape once the allocation has already been scattered. It is ranked third because it defends one write site; a second write site on the same map needs the same discipline, where allocating at the source defends them all.
Create the inner map before a nested assignment. Look the inner map up, compare it with nil, and make it only if it is absent. This is the fix for the nested shape, and the comparison is not optional decoration: it is what keeps later writes from replacing a populated inner map with an empty one.
Do not answer the panic with recover, and do not test for the defect by reading. A recovered panic leaves the write undone and the caller uninformed. A read-only test passes against the nil map exactly as it passes against a made one. The defect is a missing allocation, and only an allocation — or a test that performs a write — speaks to it.
Which fix for which cause
| What the code shows | Cause | Fix |
|---|---|---|
var m map[K]V, then an assignment |
Declared, never allocated | make at the declaration, or a literal |
A map field in a struct built with T{} |
The zero value leaves the field nil | Initialize the field in a constructor |
make inside an if or one branch |
The other path reaches the write with nil | Allocate before the branch, or guard at the write |
| A function returns nil on some path | The caller writes to the returned nil | Guard on receipt, or return a made empty map |
m[a][b] = v after make on m |
The inner map was never made | Check the inner map for nil and make it first |
A lookup, len, or range on the same map works |
Reads treat nil as empty | Not evidence the map is made; test with a write |
append on a var slice works nearby |
Slices allocate through append; maps do not |
Allocate the map explicitly |
Checklist
- Find the write first: the top frame of the trace is the assignment that panicked, and its line names the map expression. Then trace that expression back to its declaration, its constructor, or the function that returned it — the missing allocation is at that end, not at the write.
- Check every path between the allocation and the write. A
makeinside a branch, a loop, or an early-return path covers only the executions that pass through it. - For a struct, check how values are produced: a map field is nil in the zero value, so any construction route that skips the field —
T{}, a partial literal, a decode into a fresh value — hands the caller a nil map. - For a map received from a call, check the callee's returns for a nil on any path, including the paths that mean "nothing found" or "nothing saved".
- For a nested map, check both levels. The outer
makesays nothing about the inner maps, and a lookup on a missing key manufactures the nil inner map on the spot. - After the fix, exercise a write in the test, not only a read. Reads cannot distinguish a nil map from a made one; the first write is the only operation that can.
Related guides on this site
- Go Slices and Maps — Append, Length, Capacity, and Lookup — the two collection types side by side: how slices grow through
appendand how maps store through assignment, the difference this guide's panic lives in. - Fix Go "Cannot Assign To ..." Compile Errors — Addressability, Map Values, Constants, and Call Results — the compile-time assignment failures, including why a struct field reached through a map value cannot be assigned to, where this guide's failure is a map that cannot be assigned into at run time.
- Fix Go "Undefined: ..." Compile Errors — Identifiers, Scope, and Package Qualifiers — the name-resolution failures from the same first programs, where the compiler stops the build instead of the runtime stopping the write.
- Fix Go "Declared and Not Used" and "Imported and Not Used" Compile Errors — the other side of a
vardeclaration: a declared map that is only read still counts as used, which is one more reason the nil map in this guide passes every check short of a write. - Fix Go "Assignment Mismatch" and "Multiple-Value in Single-Value Context" Errors — the counting errors on assignment statements, including the two-value lookup form whose
okresult readsfalseagainst a nil map exactly as it does against a made one.
Sources
- The Go Programming Language Specification — for map types (the value of an uninitialized map is nil; a new, empty map value is made using the built-in function
make, which takes the map type and an optional capacity hint; the initial capacity does not bound the map's size, with the exception of nil maps; a nil map is equivalent to an empty map except that no elements may be added), and for index expressions (if the map is nil or does not contain an entry for the key, the index expression is the zero value for the element type; used in the two-value form it yields an additional boolean that is true only if the key is present; assigning to an element of a nil map causes a run-time panic).
Keep Exploring
The full Go hub \u2014 slices and maps, concurrency, and the standard library.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.