@@ -30,3 +30,44 @@ func example() {
30
30
func wrapContext (ctx context.Context ) context.Context {
31
31
return context .WithoutCancel (ctx )
32
32
}
33
+
34
+ // storing contexts in a struct isn't recommended, but local copies of a non-pointer struct should act like local copies of a context.
35
+ func inStructs (ctx context.Context ) {
36
+ for i := 0 ; i < 10 ; i ++ {
37
+ c := struct { Ctx context.Context }{ctx }
38
+ c .Ctx = context .WithValue (c .Ctx , "key" , i )
39
+ c .Ctx = context .WithValue (c .Ctx , "other" , "val" )
40
+ }
41
+
42
+ for i := 0 ; i < 10 ; i ++ {
43
+ c := []struct { Ctx context.Context }{{ctx }}
44
+ c [0 ].Ctx = context .WithValue (c [0 ].Ctx , "key" , i )
45
+ c [0 ].Ctx = context .WithValue (c [0 ].Ctx , "other" , "val" )
46
+ }
47
+
48
+ c := struct { Ctx context.Context }{ctx }
49
+ for i := 0 ; i < 10 ; i ++ {
50
+ c := c
51
+ c .Ctx = context .WithValue (c .Ctx , "key" , i )
52
+ c .Ctx = context .WithValue (c .Ctx , "other" , "val" )
53
+ }
54
+
55
+ pc := & struct { Ctx context.Context }{ctx }
56
+ for i := 0 ; i < 10 ; i ++ {
57
+ c := pc
58
+ c .Ctx = context .WithValue (c .Ctx , "key" , i ) // want "nested context in loop"
59
+ c .Ctx = context .WithValue (c .Ctx , "other" , "val" )
60
+ }
61
+
62
+ r := []struct { Ctx context.Context }{{ctx }}
63
+ for i := 0 ; i < 10 ; i ++ {
64
+ r [0 ].Ctx = context .WithValue (r [0 ].Ctx , "key" , i ) // want "nested context in loop"
65
+ r [0 ].Ctx = context .WithValue (r [0 ].Ctx , "other" , "val" )
66
+ }
67
+
68
+ rp := []* struct { Ctx context.Context }{{ctx }}
69
+ for i := 0 ; i < 10 ; i ++ {
70
+ rp [0 ].Ctx = context .WithValue (rp [0 ].Ctx , "key" , i ) // want "nested context in loop"
71
+ rp [0 ].Ctx = context .WithValue (rp [0 ].Ctx , "other" , "val" )
72
+ }
73
+ }
0 commit comments