Senior
What is a nil channel?
sobes.tech AI
Answer from AI
In Go, a nil channel is a channel that is not initialized and has the value nil. Such a channel cannot send or receive data, and operations on it block forever.
Example:
var ch chan int // ch == nil
// Sending or receiving from ch will block the goroutine forever
// ch <- 1 // block
// <-ch // block
Nil channels are useful for dynamic channel management, for example, in select you can include or exclude cases by assigning nil to a channel — this allows temporarily disabling a specific channel from selection.
Example of usage in select:
var ch1, ch2 chan int
ch1 = make(chan int)
ch2 = nil // temporarily disable ch2
select {
case msg := <-ch1:
fmt.Println("Received from ch1", msg)
case msg := <-ch2:
fmt.Println("Received from ch2", msg) // this case will never execute
}
Thus, a nil channel is a convenient tool for managing channel behavior in Go.