Skip to content

context-cancel-in-loop

Detect derived contexts retained across loop iterations.

Updated View as Markdown

Default severity: warning

context.WithCancel, WithTimeout, and WithDeadline retain parent or timer resources until cancellation. A defer in the surrounding function runs too late; cancel during the iteration or move the body into a helper.

Bad

for _, item := range items {
	itemCtx, cancel := context.WithCancel(ctx)
	defer cancel()
	use(itemCtx, item)
}

Good

for _, item := range items {
	if err := handleItem(ctx, item); err != nil {
		return err
	}
}

func handleItem(ctx context.Context, item Item) error {
	itemCtx, cancel := context.WithCancel(ctx)
	defer cancel()
	return use(itemCtx, item)
}
Navigation

Type to search…

↑↓ navigate↵ selectEsc close