runtime panic (nil pointer)
GoCRITICALCommonRuntime
runtime error: invalid memory address or nil pointer dereference
Quick Answer
Guard every pointer with a nil check before dereferencing; use recover() in long-running goroutines to prevent total crash.
What this means
A panic caused by dereferencing a nil pointer at runtime. The goroutine prints a stack trace and the program terminates unless recovered.
Why it happens
- 1Calling a method on a nil pointer receiver
- 2Accessing a field of a struct pointer that was never initialized
Fix
Nil-check before use
Nil-check before use
if p == nil {
return fmt.Errorf("unexpected nil pointer")
}
fmt.Println(p.Name)Why this works
Explicit nil guard converts a panic into a recoverable error before the dereference occurs.
Code examples
Guard before accessgo
if cfg == nil {
return errors.New("config is nil")
}
fmt.Println(cfg.Host)Recover in goroutinego
defer func() {
if r := recover(); r != nil {
log.Printf("recovered panic: %v", r)
}
}()Return zero value safelygo
func name(u *User) string {
if u == nil { return "" }
return u.Name
}Same error in other languages
Sources
Official documentation ↗
Go runtime
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev