How to Fix Go Nil Map Assignment Panics
In this tutorial, you'll learn about How to Fix Go Nil Map Assignment Panics. We cover key concepts, practical examples, and best practices.
Go panics with assignment to entry in nil map when you write to a map variable that has been declared but not initialized with make or a composite literal. Reading from a nil map returns the zero value without panicking, but writing causes a runtime crash.
Quick Fix
Wrong
var scores map[string]int
scores["Alice"] = 95
panic: assignment to entry in nil map
The map is declared but not initialized. A nil map cannot accept writes.
Right
scores := make(map[string]int)
scores["Alice"] = 95
fmt.Println(scores["Alice"])
95
Fix with composite literal
scores := map[string]int{
"Alice": 95,
"Bob": 87,
}
scores["Charlie"] = 92
fmt.Println(scores)
map[Alice:95 Bob:87 Charlie:92]
Fix in struct initialization
type Team struct {
Name string
Scores map[string]int
}
// Wrong:
team := Team{Name: "Red"}
team.Scores["Alice"] = 95
// panic: assignment to entry in nil map
// Right:
team := Team{
Name: "Red",
Scores: make(map[string]int),
}
team.Scores["Alice"] = 95
Fix when returning from function
func newScores() map[string]int {
return make(map[string]int)
}
func main() {
s := newScores()
s["Alice"] = 95
}
Prevention
- Always initialize maps with
make()before writing to them. - Use composite literals
map[K]V{...}for maps with initial values. - Check for nil before writing in library code:
if m == nil { m = make(map[K]V) }. - Initialize maps inside struct constructors.
- Run
go vetto detect potential nil map assignments.
DodaTech Tools
Doda Browser's Go analysis tool detects nil map assignments at compile time. DodaZIP archives Go module source code for static analysis. Durga Antivirus Pro monitors for nil map panics in production logs.
Common Mistakes with nil map error
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro