1
0
mirror of https://github.com/golang/go synced 2024-11-19 01:34:40 -07:00

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>
This commit is contained in:
Brad Fitzpatrick 2016-04-10 15:45:34 +00:00
parent e6a8daceb0
commit bd72497666
3 changed files with 21 additions and 2 deletions

View File

@ -39,6 +39,7 @@ package context
import ( import (
"errors" "errors"
"fmt" "fmt"
"reflect"
"sync" "sync"
"time" "time"
) )
@ -424,7 +425,12 @@ func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
// //
// Use context Values only for request-scoped data that transits processes and // Use context Values only for request-scoped data that transits processes and
// APIs, not for passing optional parameters to functions. // 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} return &valueCtx{parent, key, val}
} }

View File

@ -586,3 +586,16 @@ func TestCancelRemoves(t *testing.T) {
cancel() cancel()
checkChildren("after cancelling WithTimeout child", ctx, 0) checkChildren("after cancelling WithTimeout child", ctx, 0)
} }
func TestWithValueChecksKey(t *testing.T) {
panicVal := recoveredValue(func() { WithValue(Background(), []byte("foo"), "bar") })
if panicVal == nil {
t.Error("expected panic")
}
}
func recoveredValue(fn func()) (v interface{}) {
defer func() { v = recover() }()
fn()
return
}

View File

@ -215,7 +215,7 @@ var pkgDeps = map[string][]string{
"compress/gzip": {"L4", "compress/flate"}, "compress/gzip": {"L4", "compress/flate"},
"compress/lzw": {"L4"}, "compress/lzw": {"L4"},
"compress/zlib": {"L4", "compress/flate"}, "compress/zlib": {"L4", "compress/flate"},
"context": {"errors", "fmt", "sync", "time"}, "context": {"errors", "fmt", "reflect", "sync", "time"},
"database/sql": {"L4", "container/list", "database/sql/driver"}, "database/sql": {"L4", "container/list", "database/sql/driver"},
"database/sql/driver": {"L4", "time"}, "database/sql/driver": {"L4", "time"},
"debug/dwarf": {"L4"}, "debug/dwarf": {"L4"},