Goroutine Refers to Enclosing Function Variable

goroutine may access variable after function returns, causing use-after-return

Quick Answer

The goroutine outlives the function and accesses a local variable that may be garbage collected. Pass the variable as a parameter or ensure the function waits for the goroutine.

Why This Happens

When a goroutine captures a local variable from its enclosing function, and the function returns before the goroutine finishes, the variable could be modified or reclaimed. While Go's escape analysis usually handles this, it leads to confusing bugs when the variable changes unexpectedly.

The Problem

func startWorkers() {
    for i := 0; i < 5; i++ {
        go func() {
            fmt.Println(i) // always prints 5
        }()
    }
}

The Fix

func startWorkers() {
    for i := 0; i < 5; i++ {
        go func(n int) {
            fmt.Println(n) // prints 0, 1, 2, 3, 4
        }(i)
    }
}

Step-by-Step Fix

  1. 1

    Identify captured variables

    Look for goroutines that reference variables from the enclosing scope.

  2. 2

    Pass as parameter

    Pass the variable as an argument to the goroutine function to create an independent copy.

  3. 3

    Or wait for completion

    Use sync.WaitGroup to ensure the goroutine completes before the enclosing function returns.

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