Context key in Go

When using context in Go, I used to write this kind of context keys.

type contextKeyType string

const key1 = contextKeyType("key1")
const key2 = contextKeyType("key2")

Nothing wrong with this approach. But if we have 5+ keys, we would have to repeat the key name a lot since we use the key name as the key value.

type contextKeyType string

const key1 = contextKeyType("key1")
const key2 = contextKeyType("key2")
...
const key5 = contextKeyType("key5")

Recently I found a simpler approach.

type key int

const (
    key1 key = iota
    key2
    ...
    key5
)

Looks simpler!

Collision free as well

This approach would not be causing any key collision among packages that use context.

Some context on context key:

  • "Equality operator is used to check if context stores value for the desired key"
  • "Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil"
  • "A named type is always different from any other type"

Therefore, as long as we use different named types, the keys would not be colliding. In this case, the named type is private so other packages cannot use that type.

See this article for more explanation.