go
runtime
ai_generated
true
runtime error: invalid memory address or nil pointer dereference
ID: go/nil-pointer-dereference
96%Fix Rate
97%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 121 | active | — | — | — |
| 1 | active | — | — | — |
Root Cause
Attempting to dereference a nil pointer, often from unchecked error returns.
genericWorkarounds
-
96% success Add nil checks before dereferencing: if ptr != nil { ... }
if user != nil { fmt.Println(user.Name) } // For nested pointers: if resp != nil && resp.Body != nil { defer resp.Body.Close() } -
94% success Use the comma-ok idiom for map lookups and type assertions
// Map lookup: val, ok := myMap[key] if !ok { return fmt.Errorf("key %q not found", key) } // Type assertion: str, ok := iface.(string) if !ok { return fmt.Errorf("expected string, got %T", iface) }Sources: https://go.dev/doc/effective_go#interface_conversions
-
90% success Return concrete types with zero values instead of nil pointers
// Instead of returning *Config (can be nil): func NewConfig() Config { return Config{Timeout: 30 * time.Second, Retries: 3} } // Use value receivers on the zero value: var c Config // safe to use immediately
Dead Ends
Common approaches that don't work:
-
Using recover() to catch all nil pointer panics
75% fail
Masks bugs; recover should only be used at API boundaries
-
Initializing all pointers to empty structs
55% fail
Hides nil-state bugs; empty struct may not be a valid state
Error Chain
Frequently confused with: