# 恐慌：向已关闭的通道发送数据

- **ID:** `go/send-on-closed-channel`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

向已经关闭的通道发送数据。

## 版本兼容性

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

## 解决方案

1. **Ensure no sends after close by using a done channel pattern** (95% 成功率)
   ```
   done := make(chan struct{})
// producer loop
select {
case <-done:
    return
case ch <- data:
}
// closer
close(ch); close(done)
   ```
2. **Use a mutex to synchronize close and sends** (90% 成功率)
   ```
   var mu sync.Mutex
var closed bool
mu.Lock()
if closed { mu.Unlock(); return }
ch <- data
mu.Unlock()
   ```

## 无效尝试

- **Checking if channel is closed before sending via a flag** — Race condition: the channel may be closed between the check and the send. (85% 失败率)
- **Using recover() to catch panic and continue** — Recovering from panic is possible but indicates design flaw; data may be lost. (70% 失败率)
