Senior
What is the purpose of context in Go?
sobes.tech AI
Answer from AI
The Go package context is used for passing cancellation signals, deadlines, and other values across goroutines and functions. It allows controlling the lifecycle of operations, especially in network requests, data processing, and parallel computations.
Main uses of context:
- Canceling operations (e.g., on timeout or user cancellation).
- Passing a deadline (a time by which the operation should complete).
- Passing request-related values (e.g., user ID, tokens).
Example usage:
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
// Cancel after 5 seconds
def fetchData(ctx context.Context) error {
select {
case <-time.After(time.Second * 10):
// Long operation
return nil
case <-ctx.Done():
// Cancel operation
return ctx.Err()
}
}
err := fetchData(ctx)
if err != nil {
fmt.Println("Operation cancelled or timed out:", err)
}
cancel()
Thus, context helps manage the lifetime and cancellation of operations, improving control over concurrency and resources.