Middle+
What is a context in Go, how is it used, what is it for, and what types does it have?
sobes.tech AI
Answer from AI
In Go, context is a package and type used to pass cancellation signals, deadlines, and other meaningful values between goroutines and functions. The main purpose of context is to manage the lifetime of operations, especially in network requests, databases, and other long-running processes.
Context allows:
- Cancel operations (via cancellation signals).
- Pass deadlines (the time by which an operation should complete).
- Pass values (e.g., request IDs for logging).
Types of context:
context.Background()— an empty root context, usually used in main functions or tests.context.TODO()— a temporary context when it is not yet determined which to use.- Cancellable contexts (
context.WithCancel(parent)) — allow manual cancellation of an operation. - Contexts with deadlines (
context.WithDeadline(parent, time)) — canceled after the specified time. - Contexts with timeouts (
context.WithTimeout(parent, duration)) — a simplified version with a deadline. - Contexts with values (
context.WithValue(parent, key, value)) — for passing data.
Example usage:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case <-time.After(3 * time.Second):
fmt.Println("operation completed")
case <-ctx.Done():
fmt.Println("operation cancelled or timed out")
}
Thus, context helps control the execution and cancellation of operations, improving resource management and application responsiveness.