liveBook · Manning

Context.Done

As explained in Learn Go with Pocket-Sized Projects

context.Context.Done is a method that returns a channel closed when the context is canceled or reaches its deadline.

Context.Done returns a channel that closes when a context is canceled or reaches its deadline. Reading from the channel then completes immediately, so concurrent code can detect expiration without comparing deadlines with the current time. section 10.6.1 section 10.6.3

Race a response against the deadline

Use select to let whichever event happens first control the function: return the backend response, or handle <-ctx.Done() when the context expires. The cancellation branch commonly returns the context’s error; newer Go code may use context.Cause(ctx) when cancellation has a specific cause. section 10.6.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains channel closure and select-based handling, then demonstrates child-context timeouts and cancellation testing.
Examples
Uses a backend response select, a timed database call, and a mock that waits for ctx.Done().
What it assumes
Assumes familiarity with Go channels and select while defining Done within context.Context from its interface methods.
What you can do after
Apply it via Go select statements to stop waiting when a context is canceled or its deadline expires.
How it connects
Connects context.Context with deadlines, cancellation, select, context.Err, and context.Cause.

Also explained in

Compare how 2 books explain Context.Done →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.