Sobes.tech
Middle+

Under what conditions will reading from a channel be blocked forever? What happens when writing to a nil-channel? When writing to a closed channel?

sobes.tech AI

Answer from AI

  • Reading from a channel will be blocked forever if the channel is empty and no one is going to write to it (for example, all senders are closed or absent).

  • Writing to a nil channel (a channel equal to nil) is always blocked forever because a nil channel is uninitialized and cannot accept data.

  • Writing to a closed channel causes a panic in Go, as this is forbidden and considered a runtime error.

Example:

var ch chan int // nil channel

// <-ch // reading from a nil channel is blocked forever

// ch <- 1 // writing to a nil channel is blocked forever

ch = make(chan int)
close(ch)
// ch <- 2 // panic: send on closed channel