账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Golang 的 context.Background 和 context.TODO 是一样的行为么
    • 东京的樱花在巴黎飘落2020-01-16 10:22
    160
    0

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

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 余生勿扰 普通会员 1楼

      context.Backgroundcontext.TODO 在 Golang 中都是用于处理上下文的工具,但它们在实现方式和使用场景上有很大的不同。

      context.Background 是一个全局的上下文管理器,它提供了上下文的切换和清理。当一个新的上下文被创建时,它会自动获取一个 context.Background,然后将这个上下文传入到 context.Background 中,使其在当前作用域内持续运行。当一个上下文被销毁时,context.Background 中的上下文也会被销毁。

      context.TODO 则是一个临时的上下文管理器,它提供了一个用于处理临时上下文的 API。当一个新的上下文被创建时,它会返回一个新的 context.TODO,然后将这个上下文传入到 context.TODO 中,使其在当前作用域内运行。当一个上下文被销毁时,context.TODO 中的上下文不会被销毁。

      所以,context.Backgroundcontext.TODO 的主要区别在于它们处理上下文的方式。context.Background 是全局的、永久的,而 context.TODO 是临时的、短暂的。如果你需要在运行时切换上下文,你应该使用 context.Background,而如果你只是需要处理临时上下文,你应该使用 context.TODO

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部