go runtime_error ai_generated true

panic: receive from closed channel

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-02-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active
1.19 active
1.20 active
1.21 active
1.22 active

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

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

    cap() does not indicate closed state.

  2. Using recover() to ignore panic 70% fail

    Recover does not prevent data corruption.