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实例,为什么要把两者区分开呢,使用效果上有什么不一样的么?

阅读 26.3k
3 个回答

注释已经说得很清楚了

新手上路,请多包涵
TODO is recognized by static analysis tools that determine
// whether Contexts are propagated correctly in a program.

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题