What is select?
- Go course
- Intermediate
- Lesson 13/80
- 4 min
Learn to wait on multiple channels with select.
What is select?
select waits on multiple channel operations at once. It looks like switch but each case is a channel operation. The ready case runs; if several are ready one is picked at random.
select lets a goroutine react to many events. It is the standard tool for timeouts, cancellation or multiple data sources.
select structure
A select block has cases. Each case is a channel operation: case v := <-ch1: or case ch2 <- 1:. The body of the ready case runs.
If no case is ready and there is a default, it runs; otherwise select blocks. If several cases are ready Go picks one at random; this gives fair scheduling.
Practice Wait with select
Inside main, add a select { ... } block and print select ready with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
ch := make(chan string)
go func() { ch <- "select hazır" }()
select {
case m := <-ch:
fmt.Println(m)
}
}Expected output
select hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does select wait on?
- Loops
- Multiple channels Correct answer
- A single channel
- Errors
Explanation: multiple channels. For one channel <-ch is enough.
2 select block
____ {
case v := <-ch1:
fmt.Println(v)
case ch2 <- 1:
fmt.Println("sent")
}
select {
case v := <-ch1:
fmt.Println(v)
case ch2 <- 1:
fmt.Println("sent")
}
Explanation: switch compares values, select waits on channels.
3 Match select concepts
| Term | Meaning |
|---|---|
select |
Multi-wait |
case |
Channel op |
default |
When none ready |
random |
Several ready |