Go select and Timeouts
select waits on several channel operations at once. With time.After it gives you timeouts.
ExampleGo
package main
import (
"fmt"
"time"
)
func main() {
fast := make(chan string)
slow := make(chan string)
go func() {
time.Sleep(10 * time.Millisecond)
fast <- "fast result"
}()
go func() {
time.Sleep(500 * time.Millisecond)
slow <- "slow result"
}()
for i := 0; i < 2; i++ {
select {
case m := <-fast:
fmt.Println(m)
case m := <-slow:
fmt.Println(m)
case <-time.After(100 * time.Millisecond):
fmt.Println("timeout")
}
}
}Output
fast result timeout
Quick check
What does select do?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.