Go: proposal: context: add Context.IsCanceled method

Created on 27 Jun 2020  路  7Comments  路  Source: golang/go

please add function like that to the context type:
func (c Context) IsCanceled() {
select {
case <- c.Done():
return true
default:
return false
}
}
or something like that to simplify context cancelation checking in channelless situations by something like that:
if ctx.IsCanceled() {
return ctx.Err()
}

Proposal

Most helpful comment

The proposed function is the same as ctx.Err() != nil. It doesn't seem to add much. In particular the case at the bottom would normally be written

    if err := ctx.Err(); err != nil {
        return err
    }

which seems preferable to me.

All 7 comments

The proposed function is the same as ctx.Err() != nil. It doesn't seem to add much. In particular the case at the bottom would normally be written

    if err := ctx.Err(); err != nil {
        return err
    }

which seems preferable to me.

As Ian pointed out, ctx.Err is exactly this function (returning an error instead of a boolean).
In #19856, we made sure that this idiom is valid - Err is allowed before the Done channel is closed, and it must return nil.

While you could implement a func that is pure syntax sugar, I agree the justification seems weak:

package context

func IsCanceled(ctx Context) bool { return ctx.Err() == Canceled }

Based on the discussion above, this seems like a likely decline.

There鈥檚 also the issue of a logical race, the context may be canceled after the call to IsCancelled but before the code responding to that condition has run.

No change in consensus, so declined.

Forgot to close in July.

Was this page helpful?
0 / 5 - 0 ratings