context.WithValueでコンテキストに記載される値には任意の型が使えるが、キーが一意で比較可能であることを保証する必要がある
-
intをベースに独自型を定義する
- コンテキストに異なる値を記憶させる場合は、この方法を使用する
type userKey int // intをベースにしたuserKyeを定義
const (
_ userKey = iota // ゼロ値として定義
key // userKye型の1としてkeyを使用する
)
-
struct{}(空の構造体)を使ってエクスポートされていないキーの型を定義する
- キーが一つしか必要ない場合は、どちらの方法でも構わない
type userKey struct{}
package main
import (
"context"
"fmt"
)
type userKey struct{}
func main() {
ctx := context.WithValue(context.Background(), userKey{}, "hanako")
doSomething(ctx)
}
func doSomething(ctx context.Context) {
user, ok := ctx.Value(userKey{}).(string)
if ok {
fmt.Println("Hello,", user)
}
}