go type_error ai_generated true

错误:期望结果 3,得到 3(所有 goroutine 看到同一个循环变量)

error: expected result 3, got 3 (all goroutines see same loop variable)

ID: go/loop-variable-capture

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

版本兼容性

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

根因分析

在 Go 1.22 之前,for 循环内启动的 goroutine 捕获同一个循环变量,导致所有 goroutine 看到最终值。这会造成微妙的输出错误和竞态。

English

Before Go 1.22, goroutines launched inside a for loop captured the same loop variable, so all goroutines observed the final value. This causes subtle output bugs and races.

generic

解决方案

  1. 95% 成功率
    Shadow the loop variable: for _, v := range items { v := v; go func(){ use(v) }() }
  2. 92% 成功率
    Upgrade to Go 1.22+ where loop variables are per-iteration by default, or pass v as an argument: go func(v T){...}(v)

无效尝试

常见但无效的做法:

  1. 90% 失败

    The variable is shared; sleeping changes nothing about which value is read.

  2. 95% 失败

    Scheduling does not affect variable capture semantics.