go
runtime_error
ai_generated
true
恐慌:关闭nil通道
panic: close of nil channel
ID: go/goroutine-close-nil-channel
80%修复率
86%置信度
0证据数
2025-05-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
对nil通道调用close(),这是编程错误。
English
Calling close() on a nil channel, which is a programming error.
解决方案
-
99% 成功率 Initialize channel before close
ch := make(chan int) // use ch close(ch)
-
85% 成功率 Use sync.Once to safely close only if initialized
var once sync.Once if ch != nil { once.Do(func() { close(ch) }) }
无效尝试
常见但无效的做法:
-
Using recover() to catch panic
90% 失败
Recover works but doesn't fix the logic; channel remains nil.
-
Checking ch != nil before close but not initializing
80% 失败
Nil check prevents panic but channel is never initialized; subsequent operations fail.