go runtime_error ai_generated true

error: 测试失败: 所有 goroutine 捕获了相同的循环变量值

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

ID: go/range-loop-variable-capture

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-01-05首次发现

版本兼容性

版本状态引入弃用备注
1.18 active — — —
1.19 active — — —
1.20 active — — —
1.21 active — — —

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 85% 失败

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

  2. 80% 失败

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