Go: Runtime Error β Invalid Memory Address or Nil Pointer Dereference
runtime error: invalid memory address or nil pointer dereference
Youβre trying to use a pointer thatβs nil.
Why this happens
In Go, pointer variables default to nil when not explicitly initialized. When you attempt to access a field or call a method on a nil pointer, the runtime panics because thereβs no memory address to dereference. This commonly occurs when functions return nil on error and the caller doesnβt check before using the result.
Fix 1: Check for nil before using
// β user might be nil
fmt.Println(user.Name)
// β
Check first
if user != nil {
fmt.Println(user.Name)
}
Fix 2: Initialize your structs
// β Pointer is nil
var user *User
user.Name = "Alice" // Panic!
// β
Initialize
user := &User{}
user.Name = "Alice"
Fix 3: Check error returns
result, err := doSomething()
if err != nil {
log.Fatal(err)
}
// Now safe to use result
fmt.Println(result.Value)
Alternative solutions
Use value receivers instead of pointer receivers when the method doesnβt need to mutate the struct β this avoids nil pointer panics on method calls.
Return zero-value structs instead of nil from functions when possible:
// β
Returns empty struct instead of nil
func getUser() User {
return User{}
}
Prevention
- Always handle the error case before using the returned value β never skip
if err != nilchecks. - Use a linter like
nilawayorstaticcheckto catch potential nil dereferences at compile time.
Related: Go: Context Deadline Exceeded fix Β· C#: NullReferenceException fix