go-nil-map
Map nil safety - read OK, write panics
When & Why to Use This Skill
This Claude skill provides essential guidance on Go map nil safety, helping developers understand the critical distinction between reading and writing operations on nil maps. It prevents common runtime panics by offering clear initialization patterns and defensive coding strategies to ensure robust Go application development.
Use Cases
- Preventing 'assignment to entry in nil map' runtime panics by implementing proper map initialization with make().
- Implementing defensive programming patterns to safely handle maps that may be nil during execution.
- Troubleshooting and fixing crashes in Go services related to uninitialized data structures.
- Improving code quality and reliability during peer reviews by identifying unsafe map access patterns.
| name | go-nil-map |
|---|---|
| description | Map nil safety - read OK, write panics |
Map Nil Safety
Problem
Reading from nil map returns zero value. Writing to nil map panics.
Pattern
WRONG - Write to nil map
var m map[string]int // nil map
m["key"] = 42 // PANIC: assignment to entry in nil map
CORRECT - Initialize with make
m := make(map[string]int)
m["key"] = 42 // OK
Reading is Safe
var m map[string]int // nil map
v := m["key"] // OK, v = 0 (zero value)
v, ok := m["key"] // OK, v = 0, ok = false
Quick Fix
- Always initialize maps with make() before writing
- Check if map is nil before range/write
- Reading from nil map is safe but returns zero values
Defensive Pattern
if m == nil {
m = make(map[string]int)
}
m["key"] = 42