# 恐慌：运行时错误：索引超出范围 [5]，长度为 5（闭包捕获）

- **ID:** `go/goroutine-slice-iteration-closure`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

goroutine 闭包通过引用捕获循环变量，导致 goroutine 在循环后执行时索引值意外。

## 版本兼容性

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

## 解决方案

1. **Copy loop variable to a local variable inside the loop** (95% 成功率)
   ```
   for i := 0; i < 5; i++ {
    i := i
    go func() {
        fmt.Println(i)
    }()
}
   ```
2. **Pass the value as an argument to the goroutine** (95% 成功率)
   ```
   for i := 0; i < 5; i++ {
    go func(val int) {
        fmt.Println(val)
    }(i)
}
   ```

## 无效尝试

- **Using a sleep inside the loop to 'wait' for goroutines** — Does not fix closure capture; goroutines still see final index. (80% 失败率)
- **Using a different variable name inside the loop without copying** — All goroutines still reference the same variable. (70% 失败率)
