首页 > 解决方案 > 上下文中的值不能在不同的包中传递?

问题描述

今天我尝试用上下文编程,代码如下:

package main

func main(){
  ctx := context.Background()
  ctx = context.WithValue(ctx,"appid","test111")
  b.dosomething()
}


package b

func dosomething(ctx context.Context){
    fmt.Println(ctx.Value("appid").(string))
} 

然后我的程序崩溃了。我认为这是因为这些 ctx 在不同的包中

标签: go

解决方案


我建议您仅在单个任务的生命周期中使用上下文,并通过函数传递相同的上下文。您还应该了解在哪里使用上下文以及在哪里将参数传递给函数。

另一个建议是使用自定义类型从上下文中设置和获取值。

根据以上所有内容,您的程序应如下所示:

package main

import (
    "context"
    "fmt"
)

type KeyMsg string

func main() {
    ctx := context.WithValue(context.Background(), KeyMsg("msg"), "hello")
    DoSomething(ctx)
}

// DoSomething accepts context value, retrieves message by KeyMsg and prints it.
func DoSomething(ctx context.Context) {
    msg, ok := ctx.Value(KeyMsg("msg")).(string)
    if !ok {
        return
    }

    fmt.Println("got msg:", msg)
}

您可以将函数 DoSomething 移动到另一个包中,然后将其称为 packagename.DoSomething 它不会改变任何内容。


推荐阅读