Fetch the repository succeeded.
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()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。