當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO WithValue用法及代碼示例

GO語言"context"包中"WithValue"函數的用法及代碼示例。

用法:

func WithValue(parent Context, key, val any) Context

WithValue 返回與 key 關聯的值為 val 的 parent 副本。

僅將上下文值用於傳遞進程和 API 的 request-scoped 數據,而不用於將可選參數傳遞給函數。

提供的鍵必須是可比較的,並且不應該是字符串類型或任何其他內置類型,以避免使用上下文的包之間發生衝突。 WithValue 的用戶應定義自己的 key 類型。為避免在分配給 interface{} 時進行分配,上下文鍵通常具有具體類型 struct{}。或者,導出的上下文鍵變量的靜態類型應該是指針或接口。

例子:

這個例子演示了如何將一個值傳遞給上下文,以及如何在它存在時檢索它。

package main

import (
    "context"
    "fmt"
)

func main() {
    type favContextKey string

    f := func(ctx context.Context, k favContextKey) {
        if v := ctx.Value(k); v != nil {
            fmt.Println("found value:", v)
            return
        }
        fmt.Println("key not found:", k)
    }

    k := favContextKey("language")
    ctx := context.WithValue(context.Background(), k, "Go")

    f(ctx, k)
    f(ctx, favContextKey("color"))

}

輸出:

found value: Go
key not found: color

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 WithValue。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。