Skip to content

Commit 2057ad0

Browse files
dsnetgopherbot
authored andcommitted
context: improve valueCtx.String
Check for stringer on the key itself. This is useful for locally defined context key types, where there may be multiple instances of that type. For example, see http.contextKey, which can now be called after this change. For the value itself, print the type at least instead of just resorting to "<not stringer>". Change-Id: I588ef1df34e90fb9ebd83cb180fea495e1fedaa8 Reviewed-on: https://go-review.googlesource.com/c/go/+/555697 Reviewed-by: Damien Neil <[email protected]> Reviewed-by: Dmitri Shuralyov <[email protected]> Run-TryBot: Joseph Tsai <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Auto-Submit: Joseph Tsai <[email protected]> TryBot-Result: Gopher Robot <[email protected]>
1 parent dba5189 commit 2057ad0

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

src/context/context.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -740,13 +740,13 @@ func stringify(v any) string {
740740
case string:
741741
return s
742742
}
743-
return "<not Stringer>"
743+
return reflectlite.TypeOf(v).String()
744744
}
745745

746746
func (c *valueCtx) String() string {
747-
return contextName(c.Context) + ".WithValue(type " +
748-
reflectlite.TypeOf(c.key).String() +
749-
", val " + stringify(c.val) + ")"
747+
return contextName(c.Context) + ".WithValue(" +
748+
stringify(c.key) + ", " +
749+
stringify(c.val) + ")"
750750
}
751751

752752
func (c *valueCtx) Value(key any) any {

src/context/x_test.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,8 @@ func TestCanceledTimeout(t *testing.T) {
201201
type key1 int
202202
type key2 int
203203

204+
func (k key2) String() string { return fmt.Sprintf("%[1]T(%[1]d)", k) }
205+
204206
var k1 = key1(1)
205207
var k2 = key2(1) // same int as k1, different type
206208
var k3 = key2(3) // same type as k2, different int
@@ -224,13 +226,17 @@ func TestValues(t *testing.T) {
224226
c1 := WithValue(Background(), k1, "c1k1")
225227
check(c1, "c1", "c1k1", "", "")
226228

227-
if got, want := fmt.Sprint(c1), `context.Background.WithValue(type context_test.key1, val c1k1)`; got != want {
229+
if got, want := fmt.Sprint(c1), `context.Background.WithValue(context_test.key1, c1k1)`; got != want {
228230
t.Errorf("c.String() = %q want %q", got, want)
229231
}
230232

231233
c2 := WithValue(c1, k2, "c2k2")
232234
check(c2, "c2", "c1k1", "c2k2", "")
233235

236+
if got, want := fmt.Sprint(c2), `context.Background.WithValue(context_test.key1, c1k1).WithValue(context_test.key2(1), c2k2)`; got != want {
237+
t.Errorf("c.String() = %q want %q", got, want)
238+
}
239+
234240
c3 := WithValue(c2, k3, "c3k3")
235241
check(c3, "c2", "c1k1", "c2k2", "c3k3")
236242

0 commit comments

Comments
 (0)