go runtime_error ai_generated true

fatal error: all goroutines are asleep - deadlock! (receive from nil channel)

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

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active
1.19 active
1.20 active
1.21 active

Root Cause

A goroutine attempts to receive from a nil channel, which blocks indefinitely, causing a deadlock if no other goroutine can unblock it.

generic

中文

协程尝试从 nil 通道接收数据,这会导致无限阻塞,如果没有其他协程可以解除阻塞,则会导致死锁。

Workarounds

  1. 100% success Ensure channel is initialized before use
    ch := make(chan int)
    // use ch
  2. 90% success Use a default case in select to avoid blocking
    select {
    case val := <-ch:
        // process
    case <-time.After(1 * time.Second):
        // timeout
    }

Dead Ends

Common approaches that don't work:

  1. Initialize channel in init() 60% fail

    If the channel is used before init() runs, it remains nil.

  2. Ignore the nil channel and add a timeout 80% fail

    Timeout doesn't fix the root cause; the channel is still nil and will block again.