go runtime_error ai_generated true

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

ID: go/channel-send-to-nil-channel

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active

Root Cause

A goroutine attempted to send to a nil channel, which blocks forever. If no other goroutine can proceed, the runtime detects a deadlock.

generic

中文

某个 goroutine 尝试向 nil channel 发送数据,这会永久阻塞。如果没有其他 goroutine 可以继续执行,运行时会检测到死锁。

Workarounds

  1. 98% success
    ch := make(chan int)
    // or ch := make(chan int, 1)
  2. 90% success
    select {
    case ch <- v:
    case <-time.After(1 * time.Second):
        return errors.New("timeout: channel may be nil")
    }

Dead Ends

Common approaches that don't work:

  1. 90% fail

    A nil channel in a select will never be ready, so the default case will always be taken, silently dropping the send.

  2. 85% fail

    Checking for nil is not atomic and does not guarantee the channel is initialized; it may still be nil at send time.