MST
星途 面试题库

面试题:Go中如何在context中设置和获取自定义值

请描述在Go语言中,使用context包管理上下文时,如何设置一个自定义键值对,并且在后续的函数调用中获取这个值。请写出关键代码示例。
44.0万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
  1. 设置自定义键值对: 在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就是包含了自定义键值对的上下文
    }
    
  2. 在后续函数调用中获取值: 在后续函数中,可以通过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)并进行类型断言来获取值。如果类型断言成功,则说明获取到了对应的值。