登录
首页 >  Golang >  Go问答

Golang 中使用 context.TODO 会导致错误吗

来源:stackoverflow

时间:2024-03-20 19:54:20 242浏览 收藏

在 Go 语言中使用 `context.TODO` 作为上下文可能会导致意外的行为。虽然 `context.TODO` 不会取消,也没有值或截止时间,但它的 `Err()` 方法始终返回 `nil`。这与使用其他上下文不同,后者会在上下文被取消或达到截止时间时返回非零错误。因此,依赖 `context.TODO` 的代码可能会忽略上下文错误,导致程序行为不当。

问题内容

ctx = context.TODO()
cmd := exec.CommandContext(ctx, , )
fmt.Println(ctx.Err())

如果 ctx 是 context.todo(),ctx.err() 是否会变为非零?


正确答案


context.todo().err() 将始终返回 nil,这可以在 the source code 中轻松看出:

package context

// An emptyCtx is never canceled, has no values, and has no deadline.
type emptyCtx int

func (*emptyCtx) Err() error {
    return nil
}

// ...

var (
    todo       = new(emptyCtx)
)

// ...

// 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).
func TODO() Context {
    return todo
}

本篇关于《Golang 中使用 context.TODO 会导致错误吗》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>