go runtime_error ai_generated true

panic: runtime error: receive from nil channel

ID: go/channel-receive-from-nil

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-07-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

Attempting to receive from a channel that is nil, causing permanent block, but if in select with default, it may not panic; however, direct receive panics.

generic

中文

尝试从 nil 通道接收,导致永久阻塞,但如果 select 中有 default 可能不会恐慌;然而直接接收会恐慌。

Workarounds

  1. 100% success Initialize channel before use
    ch := make(chan int); go func() { ch <- 1 }(); val := <-ch
  2. 90% success Use select with default to handle nil channel gracefully
    select { case val := <-ch: use(val); default: // skip }

Dead Ends

Common approaches that don't work:

  1. Checking ch == nil before receive and returning 30% fail

    Check prevents panic but may cause silent data loss.

  2. Using recover to catch panic 50% fail

    Panic is recoverable but indicates logic error; data not received.