Multiplex channel operations with select
Multiplex channel operations with select
Use select when a goroutine can make progress through more than one channel operation. Each case contains a send or receive; one ready case runs. Without default, select waits until an operation can proceed. Unlike switch, it tests communication readiness rather than comparing values.
package main
import ( "fmt")
func main() { a := make(chan string, 1) b := make(chan string) a <- "ready" select { case v := <-a: fmt.Println(v) case v := <-b: fmt.Println(v) }}Only a has a queued value; b has no sender. The receive from a wins. A send case is ready when a receiver can accept it or a buffer has room. A receive from a closed channel is also ready, so use the two-value receive when closure matters.
Expected output:
readySelect between sending and receiving
package main
import ( "fmt")
func main() { out := make(chan int, 1) in := make(chan int) select { case out <- 7: fmt.Println("sent") case v := <-in: fmt.Println(v) } fmt.Println(<-out)}The send fits in out, so select performs it and enters that case body. Channel operands and send values are evaluated once on entry, in source order, even for unselected cases. Keep side effects out of those expressions when possible.
Expected output:
sent7Try it locally
Create two channels, one buffered with a value of 21 and one empty unbuffered. Select a receive and print twice the received value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select and cancellation 01: Multiplex channel operations with select
Check the lesson objective before moving on.
When is a buffered send ready?
What does a select without default do when nothing is ready?