Created
October 10, 2025 17:07
-
-
Save goodevilgenius/91b2291ead3008137b2531532f80d851 to your computer and use it in GitHub Desktop.
Strongly typed values from context with generics #go #golang #context #generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ctx | |
import "context" | |
// Value returns a strongly-typed value from the given context using ctx.Value. | |
// ok will be true if found in the context and if the correct type. | |
func Value[T any](ctx context.Context, key any) (val T, ok bool) { | |
if val, ok = ctx.Value(key).(T); ok { | |
return val, ok | |
} | |
var zero T | |
return zero, false | |
} | |
// AssignValue will set the value of ptr to the value from Value(ctx, key), if it's | |
// found in the context and the same type as ptr. | |
func AssignValue[T any](ctx context.Context, key any, ptr *T) bool { | |
val, ok := Value[T](ctx, key) | |
if ok { | |
*ptr = val | |
} | |
return ok | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This could be used like this: