WithCancel — manual cancellation. WithTimeout — automatic after duration.
WithCancel:
1ctx, cancel := context.WithCancel(context.Background())23// Cancel when condition met4if errorOccurred {5 cancel()6}
WithTimeout:
1// Auto-cancel after 5 seconds2ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)3defer cancel()
Key difference:
Use cases: