doc: Update golang.md (#938)

This commit is contained in:
Hao He
2025-03-11 23:44:43 +08:00
committed by GitHub
parent 13701d39ee
commit 19e258c591

View File

@ -851,6 +851,54 @@ ch <- 3
参见:[缓冲通道](https://tour.golang.org/concurrency/3) 参见:[缓冲通道](https://tour.golang.org/concurrency/3)
### Context
<!--rehype:wrap-class=col-span-2 row-span-2-->
```go
package main
import (
"context"
"fmt"
"time"
)
func main() {
// 创建根 context
ctx := context.Background() // 空 context通常作为根 context
todo := context.TODO() // 当不确定使用哪个 context 时使用
// 创建带取消功能的 context
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // 确保所有路径都调用取消函数
// 创建带超时的 context
ctx, cancel = context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
// 创建带截止时间的 context
deadline := time.Now().Add(200 * time.Millisecond)
ctx, cancel = context.WithDeadline(context.Background(), deadline)
defer cancel()
// 创建带值的 context
ctx = context.WithValue(context.Background(), "key", "value")
// 从 context 获取值
value := ctx.Value("key")
fmt.Println(value)
// 检查 context 是否已取消
select {
case <-ctx.Done():
fmt.Println("Context canceled:", ctx.Err())
default:
fmt.Println("Context still valid")
}
}
```
Golang 错误控制 Golang 错误控制
-------- --------