1 Star 0 Fork 0

码农兴哥/go-demo-2025

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
main2_3.go 627 Bytes
Copy Edit Raw Blame History
码农兴哥 authored 2026-01-15 17:56 +08:00 . demo06_context
package main
import (
"context"
"fmt"
"time"
)
// context.WithTimeout() - 超时控制
func withTimeoutExample() {
fmt.Println("=== WithTimeout 示例 ===")
// 设置2秒超时
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// 模拟一个耗时操作
result := make(chan string)
go func() {
// 模拟耗时工作(3秒)
time.Sleep(3 * time.Second)
result <- "工作完成"
}()
select {
case res := <-result:
fmt.Printf("收到结果: %s\n", res)
case <-ctx.Done():
fmt.Printf("操作超时: %v\n", ctx.Err())
}
}
func main() {
withTimeoutExample()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/rxbook/go-demo-2025.git
git@gitee.com:rxbook/go-demo-2025.git
rxbook
go-demo-2025
go-demo-2025
master

Search