Closing a closed channel in Go can result in disaster
Do you use Channels in Go? Have you ever tried to close a Channel that was already closed? I bet you got a surprise.
Channels are a great way to pass data between goroutines, but a prevalent mistake I see in Go is closing a previously closed Channel.
So what happens?
Well, your code panics, and your application crashes.
When using Channels, it is best only to close a channel from one place.
If you have a bunch of readers and a single writer, close the channel on the writer’s side.
If you have a bunch of writers and a single reader, you will need to coordinate the closing of the channel to ensure a write does not happen after closure.
Note: Thanks Reddit gang for pointing out my mistake on multiple writers.
There are many ways to use Channels, and Channels are a powerful feature of Go. But use responsibly.