Why This Happens
In Go, a nil pointer holds no address. When you try to read a field or call a method on a nil pointer, the runtime panics. This commonly occurs when a function returns a pointer and an error, and you use the pointer without checking the error first.
The Problem
type User struct {
Name string
}
func findUser(id int) *User {
return nil
}
func main() {
u := findUser(42)
fmt.Println(u.Name) // panic: nil pointer dereference
}The Fix
func main() {
u := findUser(42)
if u == nil {
fmt.Println("user not found")
return
}
fmt.Println(u.Name)
}Step-by-Step Fix
- 1
Identify the nil pointer
Read the stack trace to find the exact line where the dereference occurs and identify which variable is nil.
- 2
Trace the origin
Follow the variable back to where it was assigned. Check if the function that returned it can return nil.
- 3
Add a nil check
Add an explicit nil check before using the pointer, or ensure the function always returns a valid pointer.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free