ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5 * time.Second)) defer cancel() // do some work that might take more than 5 seconds to complete
select { case <-ctx.Done(): fmt.Println(ctx.Err()) case <-time.After(10 * time.Second): // do some work that might take more than 10 seconds to complete }This example waits for either the context to be canceled or for 10 seconds to elapse, whichever comes first. If the context is canceled, it prints the error returned by `ctx.Err()`. In conclusion, the `context` library from the `golang.org.x.net` package provides a powerful way to manage concurrency and cancellations in Go programs. The ability to set deadlines with contexts allows developers to easily control how long operations should wait before they are canceled.