IS THERE A WAY TO LIST KEYS IN CONTEXT.CONTEXT?
No there is no way to list all the keys of context.Context
. Because that type is just an interface. So what does this mean?
In general a variable can hold a concrete type or an interface. A variable with an interface type does not have any concrete type informations on it. So it would makes no difference if the interface is empty (interface{}
) or context.Context. Because they could be a lot of different types which are implementing that interface. The variable does not have a concrete type. It is just something abstract.
If you use reflection you could observe the fields and all the methods of the type which is set to that variable (with interface type). But the logic how the method Value(key interface{}) interface{}
is implemented is not fixed. It does not have to be a map. You could also make an implementation with slices, database, an own type of an hash table, ...
So there is no general way to list all the values.
type ctxKey string func main() { var key1 ctxKey = "k1" var key2 ctxKey = "k2" var key3 ctxKey = "k3" ctx := context.Background() ctx = context.WithValue(ctx, key1, "v1") ctx = context.WithValue(ctx, key2, "v2") ctx = context.WithValue(ctx, key3, "v3") fmt.Println(ctx) fmt.Printf("%v\n", ctx) for _, key := range [3]ctxKey{"k1", "k2", "k3"} { fmt.Printf("key: %v, value: %v\n", key, ctx.Value(key)) } }
zzh@ZZHPC:/zdata/Github/ztest$ go run main.go context.Background.WithValue(type main.ctxKey, val v1).WithValue(type main.ctxKey, val v2).WithValue(type main.ctxKey, val v3) context.Background.WithValue(type main.ctxKey, val v1).WithValue(type main.ctxKey, val v2).WithValue(type main.ctxKey, val v3) key: k1, value: v1 key: k2, value: v2 key: k3, value: v3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律