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 <adg@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Minux Ma <minux@golang.org>
diff --git a/src/context/context.go b/src/context/context.go
index 21dc867..c332e1f 100644
--- a/src/context/context.go
+++ b/src/context/context.go
@@ -39,6 +39,7 @@
import (
"errors"
"fmt"
+ "reflect"
"sync"
"time"
)
@@ -424,7 +425,12 @@
//
// Use context Values only for request-scoped data that transits processes and
// APIs, not for passing optional parameters to functions.
-func WithValue(parent Context, key interface{}, val interface{}) Context {
+//
+// The provided key must be comparable.
+func WithValue(parent Context, key, val interface{}) Context {
+ if !reflect.TypeOf(key).Comparable() {
+ panic("key is not comparable")
+ }
return &valueCtx{parent, key, val}
}