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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?