Context WithoutCancel Detaches From Cancellation

Derive a reporting context with WithoutCancel so parent cancellation never reaches it, while context.Cause still explains why the parent stopped.

GoResilience

Code

gosnippet
31 lines
package main

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

type jobID struct{}

func main() {
	// WithCancelCause:取消时可以携带一个具体原因
	parent, cancel := context.WithCancelCause(context.Background())
	parent = context.WithValue(parent, jobID{}, "batch-42")

	// WithoutCancel 派生:保留 Value,但父级取消不会传播过来
	child := context.WithoutCancel(parent)
	fmt.Println("child done is nil:", child.Done() == nil)
	fmt.Println("child err before cancel:", child.Err())

	// 取消父级,带上真实原因
	cancel(errors.New("disk full"))

	// 父级:Err 是笼统的 Canceled,Cause 才携带传入的原因
	fmt.Println("parent err:", parent.Err())
	fmt.Println("parent cause:", context.Cause(parent))

	// 子级:Err 恒为 nil,Value 依旧可读——善后逻辑不受取消竞态影响
	fmt.Println("child err after cancel:", child.Err())
	fmt.Println("child value after cancel:", child.Value(jobID{}))
}

How it works

Context WithoutCancel Detaches From Cancellation is built around the function main.

What to watch for

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Putting it to use

Each run prints the 6 labeled blocks child done is nil:, child err before cancel:, parent err:, parent cause:, child err after cancel:, child value after cancel: in source order.

Core lines under the microscope

parent = context.WithValue(parent, jobID{}, "batch-42")
parent, cancel := context.WithCancelCause(context.Background())
child := context.WithoutCancel(parent)

Interactive Tools for This Topic

FAQ

What does Context WithoutCancel Detaches From Cancellation print when run?
Run it as a complete program — the output lines carry labels such as `child done is nil:`, `child err before cancel:`, `parent err:`.