Go Panic: Nil Pointer Dereference — Complete Guide
What Does This Error Mean?
A nil pointer dereference happens when you try to access a field or method on a pointer that is nil (Go's equivalent of null). The program panics and crashes.
Common Causes
- Uninitialized struct pointer
- Function returning nil that you didn't check
- Map access returning zero-value pointer
How to Fix It
1. Always check for nil
result, err := doSomething()
if err != nil {
return err
}
// safe to use result now2. Initialize pointers
// Before (nil)
var p *MyStruct
// After (initialized)
p := &MyStruct{}