Senior
Have you used contexts in practice? Tell us.
sobes.tech AI
Answer from AI
Yes, I regularly used contexts in Go, especially for managing execution time and canceling operations in network requests and goroutines. Context allows passing cancel signals and deadlines through call chains, which helps avoid goroutine leaks and control execution time.
Example of usage:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case <-time.After(3 * time.Second):
fmt.Println("operation completed")
case <-ctx.Done():
fmt.Println("operation cancelled or timed out")
}
Thus, if an operation takes longer than 2 seconds, it will be interrupted, increasing the robustness and responsiveness of the application.