Junior — Middle
Have you used the WithCancel mechanism for managing context cancellation in your projects?
sobes.tech AI
Answer from AI
Yes, in Go, the WithCancel mechanism from the context package is often used to manage cancellation of operations and goroutines. It allows creating a context that can be canceled manually, which is convenient for interrupting long-running or asynchronous tasks.
Example of usage:
ctx, cancel := context.WithCancel(context.Background())
// Launch a goroutine that listens for cancellation
go func() {
<-ctx.Done()
fmt.Println("Operation canceled")
}()
// At some point, call cancel()
cancel()
This allows controlling the lifecycle of operations and preventing resource leaks.