登录
首页 >  Golang >  Go问答

怎样在 Go 语言中使用 context.WithValue() 存储和获取 context.CancelFunc 类型的值?

来源:stackoverflow

时间:2024-02-27 16:45:17 300浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《怎样在 Go 语言中使用 context.WithValue() 存储和获取 context.CancelFunc 类型的值?》,涉及到,有需要的可以收藏一下

问题内容

要在ctx中存储string类型数据,key和value都需要使用类型定义,如下所示:

    // Sample program to show how to store and retrieve
    // values from a context.
    package main
    
    import (
        "context"
        "fmt"
    )
    
    // TraceID represents the trace id.
    type TraceID string
    
    // TraceIDKey is the type of value to use for the key. The key is
    // type specific and only values of the same type will match.
    type TraceIDKey int
    
    func main() {
    
        // Create a traceID for this request.
        traceID := TraceID("f47ac10b-58cc-0372-8567-0e02b2c3d479")
    
        // Declare a key with the value of zero of type userKey.
        const traceIDKey TraceIDKey = 0
    
        // Store the traceID value inside the context with a value of
        // zero for the key type.
        ctx := context.WithValue(context.Background(), traceIDKey, traceID)
    
        // Retrieve that traceID value from the Context value bag.
        if uuid, ok := ctx.Value(traceIDKey).(TraceID); ok {
            fmt.Println("TraceID:", uuid)
        }
    
        // Retrieve that traceID value from the Context value bag not
        // using the proper key type.
        if _, ok := ctx.Value(0).(TraceID); !ok {
            fmt.Println("TraceID Not Found")
        }
    }

如何使用 context.withvalue() api 存储 context.cancelfunc 类型的值?


正确答案


你是部分正确的。您应该为上下文键使用定制类型而不是内置类型,以避免发生冲突。这种类型应该不导出,除非您希望其他包能够读取/写入您的上下文键。但是该值可以是您喜欢的任何值,例如:

package main

import (
    "context"
    "fmt"
)

type contextKey int

const (
    traceIDKey contextKey = iota
    aFunctionWhyNot
)

func main() {

    // Create a traceID for this request.
    traceID := "f47ac10b-58cc-0372-8567-0e02b2c3d479"

    // Store the traceID value inside the context with a value of
    // zero for the key type.
    ctx := context.WithValue(context.Background(), traceIDKey, traceID)

    // Retrieve that traceID value from the Context value bag.
    if uuid, ok := ctx.Value(traceIDKey).(string); ok {
        fmt.Println("TraceID:", uuid)
    }

    // Or a function
    ctx = context.WithValue(ctx, aFunctionWhyNot, func() { fmt.Println("lol, I'm a function on a context") })

    // Call it maybe
    if f, ok := ctx.Value(aFunctionWhyNot).(func()); ok {
        f()
    }
}

今天关于《怎样在 Go 语言中使用 context.WithValue() 存储和获取 context.CancelFunc 类型的值?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>