Disable select cases with nil channels
Disable select cases with nil channels
A nil channel is never ready for sending or receiving. Setting a local channel variable to nil disables its select case, while leaving the original channel object unchanged. This helps combine inputs whose lifetimes differ.
package main
import ( "fmt")
func main() { var a chan int b := make(chan int, 1) b <- 5 select { case v := <-a: fmt.Println(v) case v := <-b: fmt.Println(v) }}a is disabled because its zero value is nil. This differs from a closed channel: a closed and drained channel is always ready to return zero,false. Repeatedly selecting that closed channel without disabling it can spin.
Expected output:
5Drain two sources until both close
package main
import ( "fmt")
func total(a, b <-chan int) int { s := 0 for a != nil || b != nil { select { case v, ok := <-a: if !ok { a = nil continue } s += v case v, ok := <-b: if !ok { b = nil continue } s += v } } return s}func main() { a := make(chan int, 2) b := make(chan int, 1) a <- 2 a <- 3 b <- 10 close(a) close(b) fmt.Println(total(a, b))}The loop removes a case only after its buffered values are exhausted and ok becomes false. It exits when both local variables are nil. Without the loop condition, all remaining cases could be disabled forever. Summing avoids assumptions about interleaving.
Expected output:
15Try it locally
Write count(a,b <-chan string) int to count values until both inputs are closed or nil. Test one nil input and one closed buffered input containing two strings. Print 2.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select and cancellation 03: Disable select cases with nil channels
Check the lesson objective before moving on.
Which channel receive is never ready?
When should a closed input case be disabled while draining?