Skip to content

Commit bd72497

Browse files
committed
context: document that WithValue's key must be comparable
Also, check it and explode earlier, rather than cryptic failures later. Change-Id: I319a425f60e2bc9d005a187fbdbd153faa96411c Reviewed-on: https://go-review.googlesource.com/21799 Reviewed-by: Andrew Gerrand <[email protected]> Run-TryBot: Brad Fitzpatrick <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Minux Ma <[email protected]>
1 parent e6a8dac commit bd72497

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

src/context/context.go

+7-1
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ package context
3939
import (
4040
"errors"
4141
"fmt"
42+
"reflect"
4243
"sync"
4344
"time"
4445
)
@@ -424,7 +425,12 @@ func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
424425
//
425426
// Use context Values only for request-scoped data that transits processes and
426427
// APIs, not for passing optional parameters to functions.
427-
func WithValue(parent Context, key interface{}, val interface{}) Context {
428+
//
429+
// The provided key must be comparable.
430+
func WithValue(parent Context, key, val interface{}) Context {
431+
if !reflect.TypeOf(key).Comparable() {
432+
panic("key is not comparable")
433+
}
428434
return &valueCtx{parent, key, val}
429435
}
430436

src/context/context_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -586,3 +586,16 @@ func TestCancelRemoves(t *testing.T) {
586586
cancel()
587587
checkChildren("after cancelling WithTimeout child", ctx, 0)
588588
}
589+
590+
func TestWithValueChecksKey(t *testing.T) {
591+
panicVal := recoveredValue(func() { WithValue(Background(), []byte("foo"), "bar") })
592+
if panicVal == nil {
593+
t.Error("expected panic")
594+
}
595+
}
596+
597+
func recoveredValue(fn func()) (v interface{}) {
598+
defer func() { v = recover() }()
599+
fn()
600+
return
601+
}

src/go/build/deps_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ var pkgDeps = map[string][]string{
215215
"compress/gzip": {"L4", "compress/flate"},
216216
"compress/lzw": {"L4"},
217217
"compress/zlib": {"L4", "compress/flate"},
218-
"context": {"errors", "fmt", "sync", "time"},
218+
"context": {"errors", "fmt", "reflect", "sync", "time"},
219219
"database/sql": {"L4", "container/list", "database/sql/driver"},
220220
"database/sql/driver": {"L4", "time"},
221221
"debug/dwarf": {"L4"},

0 commit comments

Comments
 (0)