# error：所有 goroutine 看到的是循环变量最终值（i = N）而非各自迭代值

- **ID:** `go/loop-variable-capture-goroutine`
- **领域:** go
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.16 | active | — | — |
| 1.20 | active | — | — |
| 1.22 | active | — | — |

## 解决方案

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

## 无效尝试

- **** — Sleeps are not deterministic; the variable is still shared and may advance before the goroutine reads it. (85% 失败率)
- **** — Serializing execution does not change variable capture semantics; the final value bug persists. (80% 失败率)
