go runtime_error ai_generated true

恐慌:关闭nil通道

panic: close of nil channel

ID: go/goroutine-close-nil-channel

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 99% 成功率 Initialize channel before close
    ch := make(chan int)
    // use ch
    close(ch)
  2. 85% 成功率 Use sync.Once to safely close only if initialized
    var once sync.Once
    if ch != nil {
        once.Do(func() { close(ch) })
    }

无效尝试

常见但无效的做法:

  1. Using recover() to catch panic 90% 失败

    Recover works but doesn't fix the logic; channel remains nil.

  2. Checking ch != nil before close but not initializing 80% 失败

    Nil check prevents panic but channel is never initialized; subsequent operations fail.