Using struct{} for context keys

385 views
Skip to first unread message

cpu...@gmail.com

unread,
May 28, 2023, 9:01:07 AM5/28/23
to golang-nuts
I've recently stumbled across code like this https://go.dev/play/p/u3UER2ywRlr:

type clientContextKey struct{}

ctx := context.Background()
ctx = context.WithValue(ctx, clientContextKey{}, "foo")
_, ok := ctx.Value(clientContextKey{}).(string)

Naively, I had expected this to fail since I assumed that clientContextKey{} would create a new variable instance every time it was used and hence the keys would not match.

Why does this use of instantiating the struct type work here?

Thanks,
Andi

burak serdar

unread,
May 28, 2023, 11:10:33 AM5/28/23
to cpu...@gmail.com, golang-nuts
Two values A and B are equal (A==B) if A and B have the same type and the same values. In a code where

 a:=clientContextKey{}
  b:=clientContextKey{}

a==b is true, because they have the same types, and they have the same values (i.e. the empty value).

Note however:

a:=&clientContextKey{}
b:=&clientContextKey{}

It is not guaranteed that a==b, neither is it guaranteed that a!=b. The compiler may choose to allocate the same address for the zero-size variables a and b, or it may not,

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/55783f87-bad8-4ca4-9c4a-d8686ae156abn%40googlegroups.com.

Andreas Götz

unread,
May 29, 2023, 5:58:11 AM5/29/23
to golang-nuts
Thank you. Zero values are of course identical. I was only thinking about the pointer case...
Reply all
Reply to author
Forward
0 new messages