By now we’ve looked at empty structs (struct{})
, and integers as possible context key types.
Today, let’s consider string context keys.
type contextKey string
const (
KeyUserID contextKey = "user_id"
KeyTransactionID contextKey = "transaction_id"
KeyMessageID contextKey = "message_id"
)
How does this stack up against our 5 criteria?
- Must be comparable.
✅ Check.
- Use minimal memory.
✅ Using a string will typically use a bit more memory than an integer (typically 32 bytes vs 16), but still quite minimal.
- Should be readable.
This is where strings most shine. They’re readable both in code, and while debugging.
fmt.Printf("failed to read context key %s", KeyMessageID)
// prints: failed to read context key message_id
- Easy to declare multiple keys per package.
✅ Super easy!
- Nice if it works with
const
✅ Yep!
It seems strings as context keys check all the boxes! A very strong candidate. Are there any better alternatives? We’ll soon see…