New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
context: documentation could suggest how to use Context key types efficiently #17826
Comments
No need for that. You can just do: var FooKey interface{} = foo And the allocation (if any) will only be done once at program start-up, and then you can use FooKey as a key allocation-free whenever. Or make your key be an empty struct type: type MyKey struct{} And then just: context.WithValue(ctx, MyKey{}, val) ... because putting |
I found that usage of type structType1 struct{}
type structType2 struct{}
var key1 structType1
var key2 structType2
type interfaceType1 interface{}
type interfaceType2 interface{}
var key3 interfaceType1 = 1
var key4 interfaceType2 = 1
func main() {
ctx := context.Background()
ctx = context.WithValue(ctx, key1, "Yes!")
fmt.Printf("%s\n", ctx.Value(key2))
ctx = context.WithValue(ctx, key3, "Sure!")
fmt.Printf("%s\n", ctx.Value(key4))
}
// Result:
// StructKey: %!s(<nil>)
// InterfaceKey: Sure! Yes, usage of type keyType struct{}
...
context.WithValue(ctx, keyType{}, val) or with global variable (looks more natural)
|
I think you're confused about how interfaces and types in general work in Go. Your key3 and key4 are identical. See https://play.golang.org/p/fyBgLguaOb and http://research.swtch.com/interfaces |
Actually, I and people in my team know, but it coming to head only when facing issue :-) Anyway, benchmark int vs empty struct has only 2 time difference in speed:
Even speed is almost same, I think collision-free is valuable in |
CL https://golang.org/cl/33152 mentions this issue. |
#17293 - defined that usage of basic types is terrible and proposed to use private type
type key int
.But it cause allocation on each usage of context.
We can avoid allocation, by usage
type key interface{}
Here is test:
Result:
Does it make sense to use
type key interface{}
in docs?The text was updated successfully, but these errors were encountered: