創建一個基礎的context
使用BackGround函數,BackGround函數原型如下:func Background() Context {return backgroundCtx{} }
作用:
Background
函數用于創建一個空的context.Context
對象。
context.Background()
函數用于獲取一個空的context.Context
對象。這個對象沒有設置任何的截止時間(deadline),也沒有取消通道(cancelation signal),并且不包含任何鍵值對(values)。它通常被用作根context
,即在開始一個新的 goroutine 或啟動一個新的操作時,如果沒有更具體的context
可用,就可以使用context.Background()
獲取的context
。ctx := context.Background() //創建一個基礎context
ctx的類型為:實現context.Context接口的類型
?type Context interface {Deadline() (deadline time.Time, ok bool)Done() <-chan struct{}Err() errorValue(key any) any }
使用WithValue向ctx添加鍵值對
//func WithValue(parent Context, key, val any) Context ctx = context.WithValue(ctx, "userID", "123456")
定義一個函數,接收context參數
funcWithCtx := func(ctx context.Context) {//從context中檢索值if value := ctx.Value("userID"); value != nil {fmt.Println("User ID from context", value)} else {fmt.Printf("No User ID from context")}}
因為Context接口類型中有Value(key any) any
通過傳入的context對象中檢索名為“userID”的值通過【通過鍵查找值】
完整代碼
package mainimport ("context""fmt" )func main() {//func Background() Contextctx := context.Background() //創建一個基礎contextctx = context.WithValue(ctx, "userID", "123456") //使用WithValue向context中添加鍵值對//定義一個函數,接受一個context參數funcWithCtx := func(ctx context.Context) {//從context中檢索值if value := ctx.Value("userID"); value != nil {fmt.Println("User ID from context", value)} else {fmt.Printf("No User ID from context")}}funcWithCtx(ctx) //調用函數,傳遞context }