go runtime_error ai_generated true

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

ID: go/receive-on-nil-channel-blocks

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.21 active — — —
1.22 active — — —

Root Cause

A receive from a nil channel blocks forever. If the channel variable was never assigned and is used in a select or receive, the goroutine hangs permanently.

generic

中文

从 nil channel 接收会永久阻塞。若 channel 变量从未被赋值却用于 select 或接收,goroutine 将永久挂起。

Workarounds

  1. 92% success
    ch := make(chan int)
    go func() { ch <- 1 }()
    v := <-ch
    fmt.Println(v)
  2. 85% success
    select {
    case v := <-ch:
        fmt.Println(v)
    case <-ctx.Done():
        return ctx.Err()
    }

Dead Ends

Common approaches that don't work:

  1. 50% fail

    It prevents the hang but the underlying nil channel is still never populated, so the program silently times out instead of working.

  2. 70% fail

    The default case fires immediately forever, spinning in a busy loop consuming CPU.