The way to set a context key and value

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)
}

That works, but becomes a type per key and is a bit unwieldy to use. I typically do something like

type contextKey int

const (
  contextKeyRequestID contextKey = iota
  contextKeySomethingElse
  ...
)

func something(// ...) {
    // Set.
    context.WithValue(context.Background(), contextKeyRequestID, "123-ABC")
    ...
}

That is, all you need is a type of your own such as contextKey and then values of that type. The underlying type can still be something simple like a string or an integer.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.