go - 上下文中的值不能在不同的包中传递?
问题描述
今天我尝试用上下文编程,代码如下:
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 在不同的包中
解决方案
我建议您仅在单个任务的生命周期中使用上下文,并通过函数传递相同的上下文。您还应该了解在哪里使用上下文以及在哪里将参数传递给函数。
另一个建议是使用自定义类型从上下文中设置和获取值。
根据以上所有内容,您的程序应如下所示:
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 它不会改变任何内容。
推荐阅读
- ajax - tabView: event.getTab() 在 Mojarra 2.3 中总是为空 - 替代方案?
- web-scraping - 为什么每当从网站上抓取信息时都会出现此错误?
- python - 尝试从邮递员发帖时收到一条错误消息,指出“没有名为收容所的列”
- javascript - 如何在 map 函数中累积值并存储在 useState 中
- linux - 将 Windows .exe 文件转换为二进制内容
- docker - Docker:除了 docker-compose.yml 之外,如何使用 Dockerfile
- google-analytics - Google Ads 报告中未显示 GA 数据
- iframe - 如何在 javascript 中从 iframe 获取 html 代码
- r - R以编程方式读取目标
- sql - 搜索特定时间的记录