Skip to content

Go Context Values: Custom Key Collisions

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Go Context Values: Custom Key Collisions. We cover key concepts, practical examples, and best practices.

Context value keys -- Prevent key collisions by using unexported custom types instead of strings for context values.

The Problem

Using string keys for context.WithValue can collide with other packages using the same key string. Always define an unexported type for your keys.

Wrong

ctx := context.WithValue(ctx, "user_id", 42)
val := ctx.Value("user_id") // OK but collision-prone

Output:

// Another package might also use "user_id" key
type contextKey string
const userIDKey contextKey = "user_id"
ctx := context.WithValue(ctx, userIDKey, 42)
val := ctx.Value(userIDKey).(int)

Output:

// Type-safe, collision-free key

Prevention

  • Define unexported types for context keys
  • Use typed constants, not raw strings
  • Use helper functions to get/set values
  • Context values should be request-scoped only
  • Do not use context to pass optional parameters

Common Mistakes with context value key

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What should I store in context?**

Request-scoped data: user ID, request ID, auth token.

What should I NOT store in context?

Function parameters, database connections, configuration.

Is context.Value slow?

Slightly slower than direct parameters. Only for request-scoped data.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro