Golang,将上下文.TODO是否会给予错误

pqwbnv8z  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(115)
ctx = context.TODO()
cmd := exec.CommandContext(ctx, <some_cmd>, <some_arg>)
fmt.Println(ctx.Err())

ctx.Err()是否会在ctx为context.TODO()的情况下变为非零值?

mi7gmzs6

mi7gmzs61#

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
}

相关问题