dsfvsdfv23599 2018-10-16 09:08
浏览 4
已采纳

上下文中的值不能在不同的包中传输吗?

Today I try to program with context,code as follow:

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))
} 

Then my program has crashed.I think it's due to that these ctx is in different package

  • 写回答

1条回答 默认 最新

  • dongmeng1868 2018-10-16 10:55
    关注

    I suggest you to use context only in a lifetime of a single task and pass the same context through functions. Also you should understand where to use context and where just to pass arguments to functions.

    Another suggestion is to use custom types for setting and getting values from context.

    According to all above, you program should look like this:

    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)
    }
    

    You can move function DoSomething into another package and just call it as packagename.DoSomething it will change nothing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号