go
runtime_error
ai_generated
true
panic: 关闭 nil channel
panic: close of nil channel
ID: go/channel-close-nil-channel
80%修复率
90%置信度
0证据数
2024-06-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0+ | active | — | — | — |
根因分析
试图关闭一个未初始化的 channel(nil)。
English
Attempting to close a channel that has not been initialized (nil).
解决方案
-
98% 成功率
ch := make(chan int) // later close(ch)
-
90% 成功率
var once sync.Once closeCh := func() { if ch != nil { once.Do(func() { close(ch) }) } }
无效尝试
常见但无效的做法:
-
80% 失败
If the channel is nil, closing it is still a panic; you must avoid the close entirely
-
70% 失败
Recovering hides the bug and may leave resources in inconsistent state