Junior — Middle
Is it possible to pass variables through the execution context?
sobes.tech AI
Answer from AI
In Go, you can pass values through the context (context.Context) using the function context.WithValue. This allows passing variables (key-value pairs) down the call chain, for example, to pass parameters, request identifiers, etc.
However, it is important to remember:
- The context is intended for passing data related to the request or operation, not for passing large structures or business logic.
- Keys should be unique and are usually defined by types or special key types to avoid conflicts.
Example of passing a value through context:
ctx := context.Background()
ctx = context.WithValue(ctx, "userID", 42)
func doSomething(ctx context.Context) {
userID := ctx.Value("userID")
fmt.Println("User ID:", userID)
}
doSomething(ctx)
Thus, yes, variables can be passed through the context, but with caution and within recommended practices.