Junior — Middle
What is the role and purpose of context in the Go programming language?
sobes.tech AI
Answer from AI
In the Go language, context.Context is used to manage the lifetime of operations, pass cancellation signals, and transmit request-scoped values between goroutines and functions.
Main purposes of context:
- Cancel operations: allows canceling long-running or blocking operations, for example, on timeout or request cancellation.
- Pass deadlines: you can set a time after which the operation should be automatically terminated.
- Transmit values: allows passing data related to the request or operation, such as user IDs, tokens, etc.
Example of usage:
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
// Pass ctx to a function that performs a long operation
result, err := LongOperation(ctx)
if err == context.DeadlineExceeded {
fmt.Println("Operation canceled due to timeout")
}
Context helps write more manageable and responsive code, especially in networked and concurrent applications.