Go Statement on Method Value With Nil Receiver

runtime error: invalid memory address or nil pointer dereference (in goroutine)

Quick Answer

You called a method as a goroutine on a nil receiver. Check the receiver is not nil before spawning the goroutine.

Why This Happens

When you write go obj.Method(), Go evaluates obj.Method at the call site to get a function value, then launches the goroutine. If obj is nil and Method has a pointer receiver, the panic happens inside the goroutine, which can crash the program without a recover.

The Problem

type Worker struct {
    Name string
}

func (w *Worker) Run() {
    fmt.Println(w.Name)
}

func main() {
    var w *Worker
    go w.Run() // nil pointer dereference in goroutine
    time.Sleep(time.Second)
}

The Fix

func main() {
    var w *Worker
    if w != nil {
        go w.Run()
    }
    time.Sleep(time.Second)
}

Step-by-Step Fix

  1. 1

    Identify the nil receiver

    Check the goroutine stack trace to find the method call with a nil receiver.

  2. 2

    Add nil check

    Verify the receiver is not nil before spawning the goroutine.

  3. 3

    Add recovery if needed

    Consider adding a recover() in the goroutine to handle unexpected panics gracefully.

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