- Sending a value to a channel after it has been closed.
- Attempting to close a channel that has already been closed.
Panic Situation 1: Sending to a Closed Channel
In this example, we create a channel, send a couple of values, receive one value, and then close the channel. When a value is sent to the channel after it is closed, a panic occurs.Always ensure that you send all values to a channel before closing it. This practice helps you avoid runtime panics related to channel mismanagement.
Panic Situation 2: Closing an Already Closed Channel
In this scenario, we demonstrate the mistake of attempting to close a channel that has already been closed. Once a channel is closed, it should not be closed again, as doing so will also trigger a panic.Do not attempt to close a channel more than once. Ensure your program logic accounts for proper channel state to prevent such panics.
These examples highlight common pitfalls when working with channels in Go. Be diligent in sending values only when no further sends are expected after closing a channel, and avoid closing channels multiple times. That concludes this lesson. We’ll see you in the next article.