Skip to content

Instantly share code, notes, and snippets.

View paulburlumi's full-sized avatar

Paul Burlumi paulburlumi

View GitHub Profile
@ww9
ww9 / context_keys_as_struct_not_int_or_string.md
Last active May 8, 2024 04:27
Why use empty struct{} and not int or string for context.Value() key types in #go

Use struct{} as keys for context.Value() in Go

In the other file of this gist I detail why we should use struct{} as context.Value() keys and not int or string. Open gist to see main.go but the TLDR is:

	type key struct{}
	ctx = context.WithValue(ctx, key{}, "my value") // Set value
	myValue, ok := ctx.Value(key{}).(string) // Get value