How do I avoid context leaks in goroutines?

Avoiding context leaks in goroutines is crucial for effective resource management in Go applications. By understanding how to properly handle contexts, you can prevent issues related to memory leaks and ensure that your code runs efficiently.
context leaks, goroutines, Go programming, resource management, memory leaks
package main import ( "context" "fmt" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() // Ensure resources are cleaned up go func() { select { case <-time.After(3 * time.Second): fmt.Println("Operation completed") case <-ctx.Done(): // Handle context cancellation fmt.Println("Operation canceled:", ctx.Err()) } }() time.Sleep(1 * time.Second) // Simulate doing something else }

context leaks goroutines Go programming resource management memory leaks