go runtime_error ai_generated true

恐慌:运行时错误:关闭空通道

panic: runtime error: close of nil channel

ID: go/panic-runtime-error-close-of-nil-channel

其他格式: JSON · Markdown 中文 · English
95%修复率
89%置信度
1证据数
2023-01-20首次发现

版本兼容性

版本状态引入弃用备注
go1.20 active
go1.21 active
go1.22 active

根因分析

尝试使用 close(ch) 关闭一个尚未初始化(空值)的通道变量。

English

Attempting to close a channel variable that has not been initialized (nil) using close(ch).

generic

官方文档

https://go.dev/ref/spec#Close

解决方案

  1. 使用 make() 初始化通道后再使用:ch := make(chan T); defer close(ch)
  2. 在 close 前进行空值检查:if ch != nil { close(ch) } else { /* 处理空值情况 */ }
  3. 使用 sync.Once 确保 close 只调用一次且在初始化之后:var closeOnce sync.Once; closeOnce.Do(func() { close(ch) })

无效尝试

常见但无效的做法:

  1. Wrap close(ch) in a recover() block to catch the panic 70% 失败

    Recovering doesn't fix the root cause and may mask a logic error

  2. Use select with default to check if channel is nil before closing 80% 失败

    select doesn't detect nil channels at compile time; it's a runtime check that still panics if nil

  3. Set ch = make(chan T) before every close call 60% 失败

    Overwrites the existing channel and may cause goroutine leaks or lost messages