# 恐慌：关闭已关闭的通道（在 for range 中）

- **ID:** `go/goroutine-for-range-channel-close`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

关闭正在被另一个协程 range 的通道，导致 range 尝试从已关闭通道读取时引发恐慌。

## 版本兼容性

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

## 解决方案

1. **Use a separate goroutine to close the channel after all sends are done.** (100% 成功率)
   ```
   ch := make(chan int)
go func() {
    for i := 0; i < 10; i++ {
        ch <- i
    }
    close(ch)
}()
for v := range ch {
    fmt.Println(v)
}
   ```
2. **Use a sync.WaitGroup to coordinate closure.** (95% 成功率)
   ```
   var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    for i := 0; i < 10; i++ {
        ch <- i
    }
}()
go func() {
    wg.Wait()
    close(ch)
}()
for v := range ch {
    fmt.Println(v)
}
   ```

## 无效尝试

- **Closing the channel inside the range loop.** — Range loop continues until channel is closed, but closing inside causes panic on next iteration. (80% 失败率)
- **Using a defer close in the sender goroutine that ranges.** — If the sender is also the range receiver, closing inside the loop is problematic. (70% 失败率)
