← 中文资源

简体中文版本

Typed Keys 承载 Context 值

用 context.WithValue 存请求级数据:键是未导出的自定义类型,跨包不会撞键;Value 断言回具体类型,未注册的键安静返回零值。

阅读英文原文

实现说明

Typed Keys 承载 Context 值可以归结为函数 main。

使用要点

  • 直接运行文件,输出会带上标签,比如 user:、user: <none>、string key hit:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「Typed Keys 承载 Context 值」会打印什么?

运行文件本身,user:、user: <none>、string key hit: 这些前缀各对应一段演示逻辑。

核心语句

ctx = context.WithValue(ctx, userKey{}, "alice")
ctx := context.Background()

代码示例

package main

import (
	"context"
	"fmt"
)

// userKey 是未导出的自定义类型:类型不同即键不同,跨包也不会撞键
type userKey struct{}

func main() {
	ctx := context.Background()

	// 存入请求级数据:键必须是可比较类型,惯例用空结构体
	ctx = context.WithValue(ctx, userKey{}, "alice")

	// 取值时断言回具体类型:Value 沿父级 ctx 逐层查找
	if user, ok := ctx.Value(userKey{}).(string); ok {
		fmt.Println("user:", user)
	} else {
		fmt.Println("user: <none>")
	}

	// 换一个键(字符串与 userKey 类型不同)就查不到:ok=false,不会串数据
	if user, ok := ctx.Value("userKey").(string); ok {
		fmt.Println("string key hit:", user)
	} else {
		fmt.Println("string key: missing")
	}
}