package main import ( "time" "context" "fmt" ) func main() { d := time.Now().Add(50*time.Millisecond) ctx, cancel := context.WithDeadline(context.Background(), d) defer cancel() select { case <-time.After(1*time.Second): fmt.Println("overslept") case <-ctx.Done(): fmt.Println(ctx.Err()) } }
执行的结果
context deadline exceeded