go runtime_error ai_generated true

恐慌:从已关闭的通道接收数据

panic: receive from closed channel

ID: go/goroutine-receive-from-closed-channel

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-02-10首次发现

版本兼容性

版本状态引入弃用备注
1.18 active
1.19 active
1.20 active
1.21 active
1.22 active

根因分析

尝试从已关闭的通道接收数据,但仅当通道为nil时才会发生恐慌。

English

Attempting to receive from a channel that was closed while a goroutine is waiting, but the panic occurs only if the channel is nil.

generic

解决方案

  1. 95% 成功率 Use comma-ok idiom to detect closed channel
    v, ok := <-ch; if !ok { /* channel closed */ }
  2. 80% 成功率 Ensure channel is not nil before receive
    if ch != nil { v := <-ch }

无效尝试

常见但无效的做法:

  1. Checking channel with cap() before receive 90% 失败

    cap() does not indicate closed state.

  2. Using recover() to ignore panic 70% 失败

    Recover does not prevent data corruption.