You can close a channel with close(chan)
.
Main purpose of closing a channel is to notify worker goroutines that their work is done and they can finish.
This ensures you don’t leak goroutines.
Closing a channel ends range
loop over it:
https://codeeval.dev/gist/3cbab9f0627d362f3be4d52be763a3d9
A receive from closed channels returns zero value immediately:
https://codeeval.dev/gist/a52e1e0b966a13e645f79f1719b9e37a
When receiving, you can optionally test if channel is closed:
https://codeeval.dev/gist/09a10fcdb162600e022305447a332d42
Closing channel twice panics:
https://codeeval.dev/gist/9c75200b2936076cc4aa769d30e2b0b7
Sending to closed channel panics: