上下文中的值不能在不同的包中传输吗?
问题描述:
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
今天,我尝试使用上下文编程,代码如下: p>
包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)) } } code> pre >然后我的程序崩溃了,我认为是由于这些ctx位于不同的软件包中 p> div>
答
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.