0

要在 中存储string类型数据ctx,需要对 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.CancelFunc使用context.WithValue()api 存储类型的值?

4

2 回答 2

4

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

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()
    }
}
于 2021-10-05T17:10:19.657 回答
2

您可以像存储任何其他值一样在上下文中存储函数:

type cancelFuncKeyType struct{}
var cancelFuncKey =cancelFuncKeyType{}

...
newctx:=context.WithValue(oldctx,cancelFuncKey,cancelFunc)


cFunc:=newctx.Value(cancelFuncKey).(context.CancelFunc)
于 2021-10-05T16:41:22.240 回答