Senior
What is the purpose of the context in Go?
sobes.tech AI
Answer from AI
The Go package context is used for managing the lifetime of requests and operations, especially in distributed systems and when working with goroutines. It allows passing cancellation signals, deadlines, and values between functions and goroutines.
Main tasks of context:
- Canceling operations (e.g., on timeout or user request cancellation).
- Passing deadlines (the time by which an operation should complete).
- Passing context-specific values (e.g., request IDs, authentication tokens).
Example usage:
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
// Cancel after 5 seconds timeout
go func(ctx context.Context) {
select {
case <-time.After(time.Second * 10):
fmt.Println("Operation completed")
case <-ctx.Done():
fmt.Println("Operation canceled or timed out")
}
}(ctx)
// Always call cancel to release resources
cancel()
Thus, context helps control the lifecycle of operations and coordinate goroutine work.