在 go 中,使用 withvalue 函数可以向 context.context 添加键值对,实现上下文数据在函数调用链中的传递。具体步骤如下:创建一个根 context。使用 withvalue 添加键值对到 context。在需要时通过 value 方法从上下文中获取数据。
在 Go 中,[context.Context](https://pkg.go.dev/context#Context) 类型用于在函数调用链中传递上下文信息。[context.WithValue](https://pkg.go.dev/context#WithValue) 函数允许我们向上下文中添加自定义键值对,从而可以在需要时使用这些数据。
func WithValue(ctx Context, key, val interface{}) Context
其中:
让我们通过一个示例来了解如何在函数中使用 WithValue 传递上下文数据:
立即学习“go语言免费学习笔记(深入)”;
package main import ( "context" "fmt" "log" ) // 用戶資料的型態 type User struct { ID int Name string } func main() { // 創建一個根 context ctx := context.Background() // 使用 WithValue 為用戶資料添加上下文資料 // key 為 "user_id",val 為 1 ctx = context.WithValue(ctx, "user_id", 1) // 調用函式 getUserInfo,並在其中訪問上下文資料 userInfo, err := getUserInfo(ctx) if err != nil { log.Fatal(err) } fmt.Printf("用戶資訊:ID: %d, 名稱: %s\n", userInfo.ID, userInfo.Name) } // getUserInfo 函數,它從上下文資料中提取用戶 ID 並使用它查詢資料庫來獲取用戶資訊 func getUserInfo(ctx context.Context) (*User, error) { // 從上下文中獲取用戶 ID userID, ok := ctx.Value("user_id").(int) if !ok { return nil, fmt.Errorf("上下文資料中沒有使用者 ID") } // 查詢資料庫以獲取用戶資訊 // 此處省略查詢資料庫的代碼 return &User{ ID: userID, Name: "John Doe", }, nil }
在這個範例中,我們使用 WithValue 在根 context 中添加了一個键值对,其中键是 "user_id",值是 1。當我們調用 getUserInfo 時,它從上下文中提取用戶 ID,並使用它查詢資料庫獲取用戶資訊。
以上就是Golang 函数:用 WithValue 传递上下文数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号