面试题答案
一键面试package main
import (
"context"
"fmt"
"time"
)
// 模拟耗时操作的函数
func longRunningFunction(ctx context.Context) (string, error) {
select {
case <-time.After(3 * time.Second): // 模拟耗时3秒的操作
return "操作完成", nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
// 创建带有2秒超时的上下文
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
result, err := longRunningFunction(ctx)
if err != nil {
fmt.Println("操作超时:", err)
} else {
fmt.Println("操作结果:", result)
}
}