当前位置: 首页 > news >正文

站点建设网站域名抢注网站

站点建设网站,域名抢注网站,睡不着来个网址2022,阿里云医疗网站建设文章目录 前言核心是 Context 接口#xff1a;包含四个方法#xff1a;遵循规则WithCancelWithDeadlineWithTimeoutWithValue 前言 很多 Go 项目的源码#xff0c;在读的过程中会发现一个很常见的参数 ctx#xff0c;而且基本都是作为函数的第一个参数。 为什么要这么写呢… 文章目录 前言核心是 Context 接口包含四个方法遵循规则WithCancelWithDeadlineWithTimeoutWithValue 前言 很多 Go 项目的源码在读的过程中会发现一个很常见的参数 ctx而且基本都是作为函数的第一个参数。 为什么要这么写呢这个参数到底有什么用呢带着这样的疑问我研究了这个参数背后的故事。 开局一张图 核心是 Context 接口 // A Context carries a deadline, cancelation signal, and request-scoped values // across API boundaries. Its methods are safe for simultaneous use by multiple // goroutines. type Context interface {// Done returns a channel that is closed when this Context is canceled// or times out.Done() -chan struct{}// Err indicates why this context was canceled, after the Done channel// is closed.Err() error// Deadline returns the time when this Context will be canceled, if any.Deadline() (deadline time.Time, ok bool)// Value returns the value associated with key or nil if none.Value(key interface{}) interface{} }包含四个方法 Done()返回一个 channel当 times out 或者调用 cancel 方法时。Err()返回一个错误表示取消 ctx 的原因。Deadline()返回截止时间和一个 bool 值。Value()返回 key 对应的值。 有四个结构体实现了这个接口分别是emptyCtx, cancelCtx, timerCtx 和 valueCtx。 其中 emptyCtx 是空类型暴露了两个方法 func Background() Context func TODO() Context一般情况下会使用 Background() 作为根 ctx然后在其基础上再派生出子 ctx。要是不确定使用哪个 ctx就使用 TODO()。 另外三个也分别暴露了对应的方法 func WithCancel(parent Context) (ctx Context, cancel CancelFunc) func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) func WithValue(parent Context, key, val interface{}) Context遵循规则 在使用 Context 时要遵循以下四点规则 不要将 Context 放入结构体而是应该作为第一个参数传入命名为 ctx。即使函数允许也不要传入 nil 的 Context。如果不知道用哪种 Context可以使用 context.TODO()。使用 Context 的 Value 相关方法只应该用于在程序和接口中传递和请求相关的元数据不要用它来传递一些可选的参数。相同的 Context 可以传递给不同的 goroutineContext 是并发安全的。 WithCancel go复制代码func WithCancel(parent Context) (ctx Context, cancel CancelFunc) WithCancel 返回带有新 Done 通道的父级副本。当调用返回的 cancel 函数或关闭父上下文的 Done 通道时返回的 ctx 的 Done 通道将关闭。 取消此上下文会释放与其关联的资源因此在此上下文中运行的操作完成后代码应立即调用 cancel。 举个例子 这段代码演示了如何使用可取消上下文来防止 goroutine 泄漏。在函数结束时由 gen 启动的 goroutine 将返回而不会泄漏。 package mainimport (contextfmt )func main() {// gen generates integers in a separate goroutine and// sends them to the returned channel.// The callers of gen need to cancel the context once// they are done consuming generated integers not to leak// the internal goroutine started by gen.gen : func(ctx context.Context) -chan int {dst : make(chan int)n : 1go func() {for {select {case -ctx.Done():return // returning not to leak the goroutinecase dst - n:n}}}()return dst}ctx, cancel : context.WithCancel(context.Background())defer cancel() // cancel when we are finished consuming integersfor n : range gen(ctx) {fmt.Println(n)if n 5 {break}} }输出 2 3 4 5WithDeadline func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)WithDeadline 返回父上下文的副本并将截止日期调整为不晚于 d。如果父级的截止日期已经早于 d则 WithDeadline(parent, d) 在语义上等同于 parent。 当截止时间到期、调用返回的取消函数时或当父上下文的 Done 通道关闭时返回的上下文的 Done 通道将关闭。 取消此上下文会释放与其关联的资源因此在此上下文中运行的操作完成后代码应立即调用取消。 举个例子 这段代码传递具有截止时间的上下文来告诉阻塞函数它应该在到达截止时间时立刻退出。 package mainimport (contextfmttime )const shortDuration 1 * time.Millisecondfunc main() {d : time.Now().Add(shortDuration)ctx, cancel : context.WithDeadline(context.Background(), d)// Even though ctx will be expired, it is good practice to call its// cancellation function in any case. Failure to do so may keep the// context and its parent alive longer than necessary.defer cancel()select {case -time.After(1 * time.Second):fmt.Println(overslept)case -ctx.Done():fmt.Println(ctx.Err())} }输出 context deadline exceededWithTimeout func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)WithTimeout 返回 WithDeadline(parent, time.Now().Add(timeout))。 取消此上下文会释放与其关联的资源因此在此上下文中运行的操作完成后代码应立即调用取消。 举个例子 这段代码传递带有超时的上下文以告诉阻塞函数应在超时后退出。 package mainimport (contextfmttime )const shortDuration 1 * time.Millisecondfunc main() {// Pass a context with a timeout to tell a blocking function that it// should abandon its work after the timeout elapses.ctx, cancel : context.WithTimeout(context.Background(), shortDuration)defer cancel()select {case -time.After(1 * time.Second):fmt.Println(overslept)case -ctx.Done():fmt.Println(ctx.Err()) // prints context deadline exceeded}}输出 context deadline exceededWithValue func WithValue(parent Context, key, val any) ContextWithValue 返回父级的副本其中与 key 关联的值为 val。 其中键必须是可比较的并且不应是字符串类型或任何其他内置类型以避免使用上下文的包之间发生冲突。 WithValue 的用户应该定义自己的键类型。 为了避免分配给 interface{}上下文键通常具有具体的 struct{} 类型。或者导出的上下文键变量的静态类型应该是指针或接口。 举个例子 这段代码演示了如何将值传递到上下文以及如何检索它如果存在。 package mainimport (contextfmt )func main() {type favContextKey stringf : func(ctx context.Context, k favContextKey) {if v : ctx.Value(k); v ! nil {fmt.Println(found value:, v)return}fmt.Println(key not found:, k)}k : favContextKey(language)ctx : context.WithValue(context.Background(), k, Go)f(ctx, k)f(ctx, favContextKey(color)) }输出 ound value: Go key not found: color本文的大部分内容包括代码示例都是翻译自官方文档代码都是经过验证可以执行的。如果有不是特别清晰的地方可以直接去读官方文档。
http://icebutterfly214.com/news/50469/

相关文章:

  • 2025年11月人才盘点公司推荐榜单:头部企业与高成长公司优选指南
  • 2025年知名的磁吸式反弹器厂家选购指南与推荐
  • 本土开发者如何选择代码托管平台?Gitee与海外平台的差异化竞争分析
  • linux date 日期
  • JSAPIThree 地图视野控制学习笔记:让地图动起来
  • 2025年体育科技与运动表现分析国际学术会议(ICSTPA 2025)
  • 基于Simulink实现卡尔曼滤波
  • SightAI 已集成 Google Gemini 3 - sight
  • 北京口碑好的涉外离婚律师服务解析及专业团队推荐
  • 2025年11月杜甫研究学者专家评价榜:程韬光教授文化贡献全景呈现
  • 2025年11月天文馆厂家推荐榜:权威评测与综合对比分析指南
  • 2025年知名的编织金属网厂家推荐及选购指南
  • 2025年11月离婚纠纷律师推荐评价:行业榜单与详细对比解析
  • 【第7章 IO编程与异常】文件句柄(File Handle)和 Python 中的文件对象(File Object)详解
  • 2025年口碑好的连体公寓床厂家实力及用户口碑排行榜
  • 2025 最新火花机厂家推荐榜:新型 / 镜面 / 数控 / 五轴联动等全品类优选,权威测评助力精密加工选型
  • 2025年11月geo优化公司排行榜:基于多维度评估的十大优质服务商选择指南
  • 2025年评价高的GY1B25ADM比例阀厂家最新推荐排行榜
  • 2025年11月geo服务商排行榜:十大优质企业技术实力与服务指南
  • 2025年11月AI搜索优化排行榜:多维度评估服务商综合能力与行业适配性
  • 2025年11月AI搜索优化排行榜:基于行业数据的十大企业综合指南
  • 2025 年履带厂家最新推荐排行榜:钢制履带 / 履带板 / 履带钢权威测评,聚焦高性能与稳定性优质之选
  • 2025年樱花批发基地批发商排行榜,优质供应商推荐,无刺枸骨球/红叶石楠/金森女贞/苗木/栾树/樱花/紫薇/金叶复叶槭/国槐种植口碑推荐榜
  • 2025年11月石墨烯地暖安装品牌推荐排行榜单权威解析
  • 2025 最新推荐!权威测评认证光选机厂家榜:AI 多模态 + 高光谱技术,覆盖全场景分选需求废塑料/薄膜/高光谱材质/日杂分选/整瓶分选/餐盒分选光选机厂家推荐
  • 2025 最新推荐智能分选设备厂家排行榜:覆盖 260 + 材质识别 国际测评认证 再生资源 / 固废处理优选绿色分拣中心/可回收物/生活垃圾塑料薄膜智能分选设备公司推荐
  • linux c文件复制
  • 实现一种超轻量级的有线表格识别方法(有代码,可部署)
  • 信竞生家长必须要了解的几个网站
  • 2025年靠谱的液压油滤油机厂家最新TOP实力排行