Junior — Middle
Why does the function Context.WithTimeout return two values, and how are they used in timeout handling?
sobes.tech AI
Answer from AI
The context.WithTimeout function in Go returns two values:
- A new context (
Context) that is automatically canceled after the specified timeout. - A cancel function (
CancelFunc) that can be called to prematurely end work with the context.
Usage:
- The new context is used to control the execution time of operations — if the time expires, the context is canceled, and related operations receive a cancellation signal.
- The cancel function is called to free resources associated with the context if the operation finishes before the timeout.
Example:
timedCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() // ensures resources are freed
select {
case <-doWork(timedCtx):
fmt.Println("Work completed")
case <-timedCtx.Done():
fmt.Println("Timeout or cancellation")
}
Thus, the returned values allow setting a time limit and controlling operation cancellation.