Junior — Middle
Can you explain what the context.WithValue function in Go is used for and how it works?
sobes.tech AI
Answer from AI
The context.WithValue function in Go is used to create a new context that contains a key-value pair. This allows passing additional data through a chain of calls without changing function signatures.
It works like this: you pass the original context, a key, and a value, and receive a new context from which you can retrieve this value using context.Value(key).
Example:
ctx := context.Background()
ctxWithValue := context.WithValue(ctx, "userID", 42)
userID := ctxWithValue.Value("userID")
fmt.Println(userID) // Outputs: 42
It is important to use unique key types to avoid conflicts, for example, by defining your own type for keys.