Go core
Browse topics

context.WithCancel

Version
1.27
Since
1.7
Review
Draft

Summary#

context.WithCancel returns a child context and a function that cancels it. Code using the context can watch Done() for cancellation and call Err() to find the reason.

Syntax#

go
ctx, cancel := context.WithCancel(parent)
defer cancel()

Example#

go
package main

import (
	"context"
	"fmt"
)

func main() {
	parent := context.Background()
	ctx, cancel := context.WithCancel(parent)
	defer cancel()

	fmt.Println(ctx.Err() == nil)
	cancel()
	<-ctx.Done()

	fmt.Println(ctx.Err())
	fmt.Println(parent.Err() == nil)
}

Expected output#

Text
true
context canceled
true

Common mistakes#

Cancellation is cooperative. Every operation that should stop must accept the context or observe its Done channel. cancel returns without waiting for the work to finish. Defer it to release the child context's resources on every return path.

Version applicability#

The standard context package, including WithCancel, has been available since Go 1.7.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0