go runtime_error ai_generated true

panic: runtime error: index out of range [5] with length 5 (closure capture)

ID: go/goroutine-slice-iteration-closure

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-11-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.22 active

Root Cause

A goroutine closure captures a loop variable by reference, leading to unexpected index values when the goroutine executes after the loop.

generic

中文

goroutine 闭包通过引用捕获循环变量,导致 goroutine 在循环后执行时索引值意外。

Workarounds

  1. 95% success Copy loop variable to a local variable inside the loop
    for i := 0; i < 5; i++ {
        i := i
        go func() {
            fmt.Println(i)
        }()
    }
  2. 95% success Pass the value as an argument to the goroutine
    for i := 0; i < 5; i++ {
        go func(val int) {
            fmt.Println(val)
        }(i)
    }

Dead Ends

Common approaches that don't work:

  1. Using a sleep inside the loop to 'wait' for goroutines 80% fail

    Does not fix closure capture; goroutines still see final index.

  2. Using a different variable name inside the loop without copying 70% fail

    All goroutines still reference the same variable.