Golang 中使用 context.TODO 会导致错误吗
时间:2024-03-20
浏览:242
作者:佚名
在 Go 语言中使用 `context.TODO` 作为上下文可能会导致意外的行为。虽然 `context.TODO` 不会取消,也没有值或截止时间,但它的 `Err()` 方法始终返回 `nil`。这与使用其他上下文不同,后者会在上下文被取消或达到截止时间时返回非零错误。因此,依赖 `context.TODO` 的代码可能会忽略上下文错误,导致程序行为不当。
问题内容
ctx = context.TODO() cmd := exec.CommandContext(ctx, <some_cmd>, <some_arg>) 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学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
