diff --git a/docs/golang.md b/docs/golang.md index 07d152b2..d3ad676c 100644 --- a/docs/golang.md +++ b/docs/golang.md @@ -851,6 +851,54 @@ ch <- 3 参见:[缓冲通道](https://tour.golang.org/concurrency/3) +### Context + + + +```go +package main + +import ( + "context" + "fmt" + "time" +) + +func main() { + // 创建根 context + ctx := context.Background() // 空 context,通常作为根 context + todo := context.TODO() // 当不确定使用哪个 context 时使用 + + // 创建带取消功能的 context + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() // 确保所有路径都调用取消函数 + + // 创建带超时的 context + ctx, cancel = context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + + // 创建带截止时间的 context + deadline := time.Now().Add(200 * time.Millisecond) + ctx, cancel = context.WithDeadline(context.Background(), deadline) + defer cancel() + + // 创建带值的 context + ctx = context.WithValue(context.Background(), "key", "value") + + // 从 context 获取值 + value := ctx.Value("key") + fmt.Println(value) + + // 检查 context 是否已取消 + select { + case <-ctx.Done(): + fmt.Println("Context canceled:", ctx.Err()) + default: + fmt.Println("Context still valid") + } +} +``` + Golang 错误控制 --------