go data_error ai_generated true

error: all goroutines see final loop variable value (i = N) instead of their iteration value

ID: go/loop-variable-capture-goroutine

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.16 active — — —
1.20 active — — —
1.22 active — — —

Root Cause

Before Go 1.22, the loop variable is shared across iterations. Closures launched as goroutines capture the same variable, which by the time they run has advanced to the final value.

generic

中文

在 Go 1.22 之前,循环变量在各迭代间共享。作为 goroutine 启动的闭包捕获同一个变量,运行时其值已推进到最终值。

Workarounds

  1. 98% success
    for i := 0; i < n; i++ {
        i := i
        go func() { use(i) }()
    }
  2. 97% success
    // go.mod: go 1.22
    for i := 0; i < n; i++ {
        go func() { use(i) }()
    }

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Sleeps are not deterministic; the variable is still shared and may advance before the goroutine reads it.

  2. 80% fail

    Serializing execution does not change variable capture semantics; the final value bug persists.