// Chapter 39 example: giving up on slow work with time.After. // Run with: go run exercises/39/02-timeout.go package main import ( "fmt" "time" ) // slowAnswer works for the given time, then sends its answer. The channel has // room for one value, so the send never blocks, even if nobody is waiting any // more. func slowAnswer(work time.Duration) <-chan int { answer := make(chan int, 1) go func() { time.Sleep(work) answer <- 42 }() return answer } // ask waits for an answer, but not for longer than limit. func ask(work time.Duration, limit time.Duration) { select { case n := <-slowAnswer(work): fmt.Println("The answer is", n) case <-time.After(limit): fmt.Println("Gave up after", limit) } } func main() { ask(200*time.Millisecond, time.Second) ask(3*time.Second, time.Second) }