Junior — Middle
What is the context in goroutine and how is it used?
sobes.tech AI
Answer from AI
In Go, the context.Context is an object used to pass cross-cutting data between goroutines, such as deadlines, cancellation signals, and request-related values. The context helps manage the lifetime of goroutines and cancel their execution if necessary.
Main uses of context:
- Canceling goroutine work (e.g., on timeout or request cancellation)
- Passing a deadline (the time by which the operation should complete)
- Passing request-related values (e.g., user ID or token)
Example of usage:
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
select {
case <-time.After(time.Second * 10):
fmt.Println("operation completed")
case <-ctx.Done():
fmt.Println("operation cancelled or timed out")
}
Thus, context allows controlling goroutine execution and passing necessary parameters without using global variables.