Junior — Middle
Использовал ли ты метод Context.WithTimeout для ограничения времени выполнения операций?
sobes.tech AI
Answer from AI
Yes, the context.WithTimeout method in Go is often used to limit the execution time of operations, especially when working with network requests, databases, or other long-running processes.
It creates a new context that is automatically canceled after the specified duration, which helps to avoid hangs and control timeouts.
Example of usage:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err := doSomething(ctx)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("Operation exceeded the timeout")
} else {
fmt.Println("Execution error:", err)
}
}
In this example, the doSomething function should support the context and cancel its work if the time runs out.