Sobes.tech
Senior

What is a context in Go? How does context.WithTimeout differ from context.WithDeadline?

sobes.tech AI

Answer from AI

In Go, the context package is used to pass cancellation signals, deadlines, and other values between goroutines, which helps manage the lifetime of operations and their cancellation.

  • context.WithTimeout(parent, timeout) creates a new context that is automatically canceled after the specified duration timeout from the current moment.

  • context.WithDeadline(parent, deadline) creates a new context that is canceled at a specific time deadline.

The main difference: WithTimeout sets a waiting time relative to the current moment, while WithDeadline sets an absolute time. Internally, WithTimeout is implemented through WithDeadline, calculating the deadline as time.Now() + timeout.

Example:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

select {
case <-time.After(10 * time.Second):
    fmt.Println("operation completed")
case <-ctx.Done():
    fmt.Println("timeout reached")
}