Golang中,context.TODO会产生错误吗?

huangapple go评论73阅读模式
英文:

Golang, will context.TODO ever give error

问题

ctx.Err()在ctx为context.TODO()时是否会变为非nil值?

英文:
ctx = context.TODO()
cmd := exec.CommandContext(ctx, <some_cmd>, <some_arg>)
fmt.Println(ctx.Err())

Is ctx.Err() is ever going to non-nil with ctx being context.TODO()?

答案1

得分: 2

context.TODO().Err()将始终返回nil,可以在源代码中轻松地看到:

package context

// emptyCtx表示未被取消、没有值和没有截止日期的上下文。
type emptyCtx int

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

// ...

var (
	todo = new(emptyCtx)
)

// ...

// TODO返回一个非nil的空上下文。当不清楚要使用哪个上下文或者上下文尚不可用(因为周围的函数尚未扩展为接受上下文参数)时,代码应该使用context.TODO。
func TODO() Context {
	return todo
}
英文:

context.TODO().Err() will always return nil, as can be easily seen in 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
}

huangapple
  • 本文由 发表于 2022年10月25日 13:34:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/74189479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定