gogo-context

Golang, will context.TODO ever give error


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()?


Solution

  • 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
    }