前置知识: Go

Context详解

00:00
1 min Intermediate 2026/6/14

context.Context与取消传播

1. 基本用法

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

result, err := fetchWithTimeout(ctx, url)

2. 传播取消

func handler(ctx context.Context) {
  go func() {
    select {
    case <-ctx.Done():
      log.Println("Cancelled:", ctx.Err())
    case <-time.After(10 * time.Second):
      log.Println("Done")
    }
  }()
}

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式