context
https://pkg.go.dev/context
簡介:
WithCancel
WithDeadline
WithTimeout
WithValuecontext.Background()func someHandler() {
ctx, cancel := context.WithCancel(context.Background()) // 利用context產生cancel方法
valueCtx := context.WithValue(ctx, key, 1)
go doStuff(valueCtx)
time.Sleep(10 * time.Second)
cancel()
}
func doStuff(ctx context.Context) {
for {
select {
case <-ctx.Done(): // cancel 時會觸發
fmt.Println(ctx.Value(key))
return
default:
//取出值
var value int = ctx.Value(key).(int)
}
}
}Context vs Channel
Last updated