context

context.WithCancel, Done, and Err: cancellation is a signal that work must observe. Examples wait on Done and do not use timer races.

The context package carries deadlines, cancellation signals, and request-scoped values across API boundaries. Canceling a context does not stop work by itself. A function keeps running until it observes ctx.Done() or ctx.Err() and returns. This page uses context.WithCancel only. It does not use WithTimeout or WithDeadline, so the examples do not depend on a race with a timer.

Official documentation says the close of the Done channel may happen asynchronously after the cancel function returns. The examples therefore wait on <-ctx.Done() after cancel before they read Err. They were checked with Go 1.24.0.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
context.WithCancel, Context.Done, Context.ErrDerive a cancelable context, wait on Done after cancel, and read context.Canceled. Do not assume Err is set before Done is closed.
Context.Done, Context.ErrCancellation is only a signal. Code that does not select on Done or check Err keeps running; code that does observe it can stop and return ctx.Err().

WithCancel, Done, and Err

context.Background is never canceled; its Done channel is nil and Err is nil. context.WithCancel derives a child context and a cancel function. After cancel is called and Done is closed, Err is context.Canceled and stays that error on later calls. Official documentation says the cancel function should be called as soon as the operations running in that context complete; calling it more than once is safe. The second cancel in the example does not change Err.

context.WithCancel, Context.Done, Context.Err

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
func Background() Context
func (c Context) Done() <-chan struct{}
func (c Context) Err() error

Derive a cancelable context, wait on Done after cancel, and read context.Canceled. Do not assume Err is set before Done is closed.

ParameterDescription
parentThe parent context, usually context.Background or a request context. Canceling the parent also cancels the child.

Returns: WithCancel returns a derived Context and a CancelFunc. After Done is closed, Err returns context.Canceled for this construction. Before cancellation, Err returns nil.

  • context.Canceled is the sentinel "context canceled". The example uses errors.Is to match it.
  • A select on Background().Done() would block forever because that Done channel is nil. This page does not demonstrate a hang.
go
package main

import (
	"context"
	"errors"
	"fmt"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	fmt.Println(ctx.Err() == nil)
	cancel()
	<-ctx.Done()
	fmt.Println(ctx.Err())
	fmt.Println(errors.Is(ctx.Err(), context.Canceled))
	cancel()
	fmt.Println(ctx.Err())
}

Expected output

true
context canceled
true
context canceled

Official documentation →

Observing cancellation

After the context is canceled, ordinary statements still run if they never look at the context. The first prints in the example increment a counter after cancel; that work is not undone. The work helper returns only when it receives from ctx.Done or when it finishes its loop. When it is called on an already canceled context, it returns 0 and ctx.Err() immediately. When it is called on a live context, it returns 3 and a nil error. There is no sleep and no concurrent cancel.

Context.Done, Context.Err

func (c Context) Done() <-chan struct{}
func (c Context) Err() error

Cancellation is only a signal. Code that does not select on Done or check Err keeps running; code that does observe it can stop and return ctx.Err().

ParameterDescription
ctxThe context passed into work. The example cancels one context before calling work, and leaves a second context live.

Returns: work returns the number of default-branch steps it ran and a nil error, or the count so far and ctx.Err() when Done is already closed.

  • The helper is called after cancel and after waiting on Done, or on a context that is never canceled during the call. That keeps the output deterministic.
go
package main

import (
	"context"
	"fmt"
)

func work(ctx context.Context) (int, error) {
	n := 0
	for {
		select {
		case <-ctx.Done():
			return n, ctx.Err()
		default:
			n++
			if n == 3 {
				return n, nil
			}
		}
	}
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	<-ctx.Done()
	n := 0
	n++
	fmt.Println(n, ctx.Err())
	got, err := work(ctx)
	fmt.Println(got, err)
	ctx2, cancel2 := context.WithCancel(context.Background())
	defer cancel2()
	got, err = work(ctx2)
	fmt.Println(got, err)
}

Expected output

1 context canceled
0 context canceled
3 <nil>

Official documentation →