Skip to content

Day 15 - Context ​

context包 ​

go
import "context"

func f(ctx context.Context) {
    // 从context获取值
    value := ctx.Value("key")
    fmt.Println(value)
}

创建Context ​

go
// 根context
ctx := context.Background()

// 带取消
ctx, cancel := context.WithCancel(ctx)

// 带超时
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)

// 带值
ctx := context.WithValue(ctx, "key", "value")

面试考点 ​

问题:Context的作用? ​

答案:

  1. 传递请求范围的值
  2. 控制取消(超时、主动取消)
  3. 避免goroutine泄漏

📅 学习进度 ​

Day主题状态
01-14基础✅
15Context✅
16单元测试⬜

本文为Go 30天学习计划第15天内容 ​

📚 导航 ​

| ← Day 14 - 上一章 | Day 16 - 下一章 →

最后更新: