H5W3
当前位置:H5W3 > go > 正文

【go】Golang 的 context.Background 和 context.TODO 是一样的行为么

Golang 中的 context 包提供了 Background 方法和 TODO 方法,用来返回一个emptyContext

源代码如下

var (
background = new(emptyCtx)
todo       = new(emptyCtx)
)
// Background returns a non-nil, empty Context. It is never canceled, has no
// values, and has no deadline. It is typically used by the main function,
// initialization, and tests, and as the top-level Context for incoming
// requests.
func Background() Context {
return background
}
// TODO returns a non-nil, empty Context. Code should use context.TODO when
// it's unclear which Context to use or it is not yet available (because the
// surrounding function has not yet been extended to accept a Context
// parameter). TODO is recognized by static analysis tools that determine
// whether Contexts are propagated correctly in a program.
func TODO() Context {
return todo
}

如上, todo 和background 都是一个emtyCtx实例,为什么要把两者区分开呢,使用效果上有什么不一样的么?

注释已经说得很清楚了

TODO is recognized by static analysis tools that determine
// whether Contexts are propagated correctly in a program.

todo 会有其他的代码审查工具来检查

你这个回复还不如不回

回答

本文地址:H5W3 » 【go】Golang 的 context.Background 和 context.TODO 是一样的行为么

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址