为了账号安全,请及时绑定邮箱和手机立即绑定

context中的值不能在不同的包中传输?

context中的值不能在不同的包中传输?

Go
牧羊人nacy 2023-04-24 16:22:25
今天我尝试使用上下文编程,代码如下:package mainfunc main(){  ctx := context.Background()  ctx = context.WithValue(ctx,"appid","test111")  b.dosomething()}package bfunc dosomething(ctx context.Context){    fmt.Println(ctx.Value("appid").(string))} 然后我的程序崩溃了。我认为这是由于这些 ctx 在不同的包中
查看完整描述

1 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

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


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


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


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 它不会改变任何内容。


查看完整回答
反对 回复 2023-04-24
  • 1 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信