面试题答案
一键面试- 设置自定义键值对:
在Go语言中,可以使用
context.WithValue
函数来设置自定义键值对。键和值可以是任意类型,但通常建议键是一个struct
类型,以避免命名冲突。package main import ( "context" "fmt" ) type customKey struct{} func main() { ctx := context.Background() value := "自定义值" ctx = context.WithValue(ctx, customKey{}, value) // 这里ctx就是包含了自定义键值对的上下文 }
- 在后续函数调用中获取值:
在后续函数中,可以通过
ctx.Value(key)
方法来获取对应的值。package main import ( "context" "fmt" ) type customKey struct{} func process(ctx context.Context) { value, ok := ctx.Value(customKey{}).(string) if ok { fmt.Println("获取到的值:", value) } else { fmt.Println("未获取到值") } } func main() { ctx := context.Background() value := "自定义值" ctx = context.WithValue(ctx, customKey{}, value) process(ctx) }
上述代码中,首先定义了一个customKey
类型作为键,然后使用context.WithValue
设置键值对。在process
函数中,通过ctx.Value(key)
并进行类型断言来获取值。如果类型断言成功,则说明获取到了对应的值。