实现说明
Context 超时与取消传播以函数 slowQuery、main为骨架。
失败在这里是值:1 处检查 err 并当场决定,而不是让它向上冒。goroutine 加 channel 的组合切分了生产与消费,同时保证交接无竞态。无论函数体里发生什么,defer 的调用都会在离开时最后执行。
使用要点
error在返回元组里,失败意味着什么由每个调用方决定。- 直接运行文件,输出会带上标签,比如
deadline exceeded:、failed:、got:——输出的每一行都能指回产生它的那次调用。 main的演示流程是slowQuery——跑一遍文件,这条流程从头到尾可见。
常见问题
错误处理是什么风格?
Go 的惯用法:err 随调用返回,这里有 1 个检查点先测它再继续。
运行「Context 超时与取消传播」会打印什么?
运行文件本身,deadline exceeded:、failed:、got: 这些前缀各对应一段演示逻辑。
入口签名:func slowQuery(ctx context.Context, key string) (string, error)
核心语句
return "", fmt.Errorf("query %q: %w", key, ctx.Err())
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("deadline exceeded:", err)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
代码示例
package main
import (
"context"
"errors"
"fmt"
"time"
)
func slowQuery(ctx context.Context, key string) (string, error) {
// 模拟一个可被取消的阻塞调用:select 监听 ctx.Done()
result := make(chan string, 1)
go func() {
time.Sleep(300 * time.Millisecond) // 模拟耗时
result <- "value-for-" + key
}()
select {
case value := <-result:
return value, nil
case <-ctx.Done():
// 上下文超时/取消时,err 一定非 nil
return "", fmt.Errorf("query %q: %w", key, ctx.Err())
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel() // 无论成败都释放定时器
value, err := slowQuery(ctx, "user-42")
if err != nil {
// errors.Is 识别根因:DeadlineExceeded 或 Canceled
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("deadline exceeded:", err)
return
}
fmt.Println("failed:", err)
return
}
fmt.Println("got:", value)
}