A developer wrote this `select` statement inside a loop, intending to time out after 1 second. What is the bug in this code?

Go & Rust interview question for Advanced practice.

Answer

time.After creates a new timer object on each loop iteration. If the timeout case is frequently chosen, this can lead to a memory leak as old timers are not garbage collected promptly.

Explanation

Option B is correct. The time.After function creates a new Timer object on every call. In a loop, if the timeout case is selected, the timer associated with the other cases may not be garbage collected immediately. This can lead to a resource leak. The preferred way to handle timeouts inside a loop is to create a single time.NewTimer before the loop and use its Reset method within the loop.

Related Questions