go runtime_error ai_generated true

error: test failed: all goroutines captured same loop variable value

ID: go/range-loop-variable-capture

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.19 active — — —
1.20 active — — —
1.21 active — — —

Root Cause

Before Go 1.22, the loop variable is shared across iterations. Closures or goroutines launched in a for loop capture the same variable, so they all see the final value.

generic

中文

在 Go 1.22 之前,循环变量在各次迭代间共享。在 for 循环中启动的闭包或 goroutine 捕获同一个变量,因此都看到最终值。

Workarounds

  1. 97% success
    for _, v := range items {
        v := v
        go func() { use(v) }()
    }
  2. 95% success
    // go.mod: go 1.22
    for _, v := range items {
        go func() { use(v) }()
    }

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Non-deterministic; the variable still changes under the goroutine and results vary.

  2. 80% fail

    Does not change the fact that the variable is shared; masking the race.