Hi,
I’ve been setting and getting a context key and it’s value as shown below.
type requestID string
const RequestIDKey = requestID("request_id")
func something(// ...) {
// Set.
context.WithValue(context.Background(), RequestIDKey, "123-ABC")
// Get.
xxx.Context().Value(CtxReqIDKey).(string)
}
However, I just want to find out if the way below can be consider as “better” approach or not because the documentation doesn’t mention if the key should be Composite Type or Basic Type.
The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context.
As far as my understanding (documentation) is concerned, version below is better because no “built-in” type is used. It uses a struct (Composite Type) instead. Just need confirmation though so please add your input. I am not saying the one above is “bad” because it doesn’t directly use a string (Basic Type) either!
Thanks
type RequestIDKey struct{}
func something(// ...) {
// Set.
context.WithValue(context.Background(), RequestIDKey{}, "123-ABC")
// Get
xxx.Context().Value(RequestIDKey{}).(string)
}