Select On Done To Cancel A Receive
Race a slow channel receive against a closed done channel so a cancelled waiter exits immediately instead of blocking forever.
Code
package main
import (
"fmt"
"time"
)
func main() {
slow := make(chan string) // 没有人往里发送
done := make(chan struct{})
go func() {
time.Sleep(20 * time.Millisecond)
close(done) // 关闭即广播:所有等待者同时被唤醒
}()
select {
case v := <-slow:
fmt.Println("received:", v)
case <-done:
fmt.Println("cancelled before any value arrived")
}
// 关闭后的 done 再次接收也不再阻塞,ok 为 false
_, ok := <-done
fmt.Println("done still open:", ok)
}How it works
Select On Done To Cancel A Receive reduces to the function main.
Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts.
Caveats
- Self-contained — no imports beyond what the runtime already provides.
Using it
Signature: func main()
The demo output is labeled (received:, cancelled before any value arrived, done still open:); each label names the call that printed it.
Key statements
done := make(chan struct{})
slow := make(chan string) // 没有人往里发送
_, ok := <-done
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Select On Done To Cancel A Receive print when run?
- Running the file directly is enough — expect labeled output lines such as `received:`, `cancelled before any value arrived`, `done still open:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.