Sobes.tech
Senior

What happens when writing to an uninitialized (nil) channel?

sobes.tech AI

Answer from AI

In Go, writing to an uninitialized (nil) channel causes the goroutine to block forever, because a nil channel is not ready to send or receive data.

Example:

var ch chan int // ch == nil

func main() {
    ch <- 1 // blocks forever, because the channel is nil
}

This behavior is sometimes used for dynamically enabling/disabling channels in select statements, since operations on a nil channel never execute and block the goroutine.

What happens when writing to an uninitialized (nil)… - sobes.tech