8. Why is time.After inside a busy for-select loop often a mistake for an overall timeout?
- time.After panics after the first use
- time.After cannot be used in select
- A new timer is created every iteration, so the timeout restarts whenever another case fires
- It makes the select choose cases in order
Show answer
Answer: A new timer is created every iteration, so the timeout restarts whenever another case fires
Create one timer before the loop, or use a context with a deadline.
Lesson: Timeouts, Timers and Tickers
9. Why set a closed input channel variable to nil inside a merge loop?
- It frees the channel memory immediately
- Setting it to nil reopens the channel
- A closed channel is always ready and returns zero values, while a nil channel case is never selected
- select panics on closed channels
Show answer
Answer: A closed channel is always ready and returns zero values, while a nil channel case is never selected
Without the nil assignment the loop would spin on zero values from the closed channel.
Lesson: The nil-Channel Trick