Junior — Middle
Can you list various scenarios of using context in programming or system architecture?
sobes.tech AI
Answer from AI
In Go, context is used to pass information about the execution state, cancel operations, and deadlines between goroutines and functions. Main scenarios for using context:
- Cancel operations: allows canceling long-running or blocking operations, for example, when shutting down a server or canceling a request.
- Passing deadlines: you can set a time after which the operation should be aborted.
- Passing values: context can contain key-value pairs, such as request identifiers, authentication tokens.
- Synchronization: helps coordinate the work of multiple goroutines to ensure they complete correctly.
Example of usage:
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
// pass ctx to a function that can be canceled by timeout
result, err := doSomething(ctx)
Thus, context helps manage the lifecycle of operations and pass metadata.