package main
import (
"fmt"
"time"
)
func main() {
first := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second) // wait 2 seconds before send value to channel
first <- "first result" // send value to the channel
}()
select {
case result := <-first:
fmt.Println(result)
case <-time.After(time.Second): // timeout occurs before the value is read from the first channel
fmt.Println("first timeout")
}
second := make(chan string, 1)
go func() {
time.Sleep(time.Second) // wait 1 second before send value to the channel
second <- "second result" // send value to the channel
}()
select {
case result := <-second: // the value from the channel is read before the timeout expires
fmt.Println(result)
case <-time.After(2 * time.Second):
fmt.Println("second timeout")
}
}
// $ go run timeouts.go
// first timeout
// second result
Timeouts are important for programs that connect to external resources or need to limit their execution time.