context.WithTimeout

What will be printed when the code below is executed?

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. func main() {
  8. timeout := 3 * time.Second
  9. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  10. defer cancel()
  11. select {
  12. case <-time.After(1 * time.Second):
  13. fmt.Println("waited for 1 sec")
  14. case <-time.After(2 * time.Second):
  15. fmt.Println("waited for 2 sec")
  16. case <-time.After(3 * time.Second):
  17. fmt.Println("waited for 3 sec")
  18. case <-ctx.Done():
  19. fmt.Println(ctx.Err())
  20. }
  21. }

Answer

  1. waited for 1 sec