diff options
| author | Joe Tsai <joetsai@digital-static.net> | 2024-01-12 17:35:48 -0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-01-12 17:35:48 -0800 |
| commit | 241a541864151d08153a5a51227e44a5c4c81e0b (patch) | |
| tree | d93ca12631b200dd04d4d6e6609a16c46eba5e7a /util/execqueue/execqueue.go | |
| parent | c9fd166cc6d85308ed987a04cf715125efead557 (diff) | |
| download | tailscale-241a541864151d08153a5a51227e44a5c4c81e0b.tar.xz tailscale-241a541864151d08153a5a51227e44a5c4c81e0b.zip | |
util/ctxkey: add package for type-safe context keys (#10841)
The lack of type-safety in context.WithValue leads to the common pattern
of defining of package-scoped type to ensure global uniqueness:
type fooKey struct{}
func withFoo(ctx context, v Foo) context.Context {
return context.WithValue(ctx, fooKey{}, v)
}
func fooValue(ctx context) Foo {
v, _ := ctx.Value(fooKey{}).(Foo)
return v
}
where usage becomes:
ctx = withFoo(ctx, foo)
foo := fooValue(ctx)
With many different context keys, this can be quite tedious.
Using generics, we can simplify this as:
var fooKey = ctxkey.New("mypkg.fooKey", Foo{})
where usage becomes:
ctx = fooKey.WithValue(ctx, foo)
foo := fooKey.Value(ctx)
See https://go.dev/issue/49189
Updates #cleanup
Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Diffstat (limited to 'util/execqueue/execqueue.go')
0 files changed, 0 insertions, 0 deletions
