go runtime_error ai_generated true

fatal error: all goroutines are asleep - deadlock! (goroutine 1 [chan receive (nil chan)])

ID: go/nil-channel-block-forever

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active
1.22 active

Root Cause

Sending or receiving on a nil channel blocks forever. This happens when a channel variable is not initialized before use.

generic

中文

在 nil 通道上发送或接收会永远阻塞。这发生在通道变量未初始化就使用的情况下。

Workarounds

  1. 95% success
    ch := make(chan int) // or with buffer: make(chan int, 10)
  2. 85% success
    var ch chan int
    select {
    case v := <-ch:
        // will not execute if ch is nil
    case <-time.After(time.Second):
        // handle timeout
    }

Dead Ends

Common approaches that don't work:

  1. 80% fail

    The default case may execute incorrectly, and the nil channel still blocks if not handled properly.

  2. 90% fail

    Nil channel is a different type; assigning doesn't initialize it.