今天我嘗試使用上下文編程,代碼如下: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 它不會改變任何內容。
- 1 回答
- 0 關注
- 107 瀏覽
添加回答
舉報
0/150
提交
取消