首页 > 后端开发 > Golang > 正文

Go Context — TODO() 与 Background() 不再令人困惑!

PHPz
发布: 2024-09-10 06:33:32
原创
713 人浏览过

Go Context — TODO() vs Background() No more confusing!

In Go, the context package helps manage request-scoped values, cancellation signals, and deadlines.
Two common ways to start a context are context.TODO() and context.Background().
Though they behave similarly, they serve different purposes.

context.Background()

context.Background() is the default when you don’t need any special handling (like cancellation or deadlines).
It's often used in main, init, or when initializing operations that don't need a more specific context.

Example:

 func main() {
     ctx := context.Background()
     server := http.Server{Addr: ":8080", BaseContext: func(net.Listener) context.Context {
         return ctx
     }}
     log.Fatal(server.ListenAndServe())
 }
登录后复制

In this example, context.Background() is used to establish a base context for the HTTP server.

context.TODO()

context.TODO() is a placeholder context. Use it when you're unsure of what context to provide or when planning to refactor later.

Example:

 func processOrder() {
     ctx := context.TODO() // Placeholder, decision on context pending
     err := db.SaveOrder(ctx, orderData)
     if err != nil {
         log.Println("Failed to save order:", err)
     }
 }
登录后复制

Here, context.TODO() is temporarily used for a database operation until a more specific context is defined.

Key Differences

Both functions return an empty context, but they express different intentions:

  • context.Background(): Used when you're confident no special context features are needed.
  • context.TODO(): A temporary placeholder context, signaling future changes.

Conclusion

When to Use context.Background():

  • When initializing core services like HTTP servers or database connections.
  • When there's no need for cancellation, deadlines, or values.

When to Use context.TODO():

  • When refactoring, and you haven’t decided on the context yet.
  • When implementing early-stage code that requires future improvements.

以上是Go Context — TODO() 与 Background() 不再令人困惑!的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!