In Go, closing a channel does not clear its buffered values; any remaining buffered data can still be received after closing.
Complete Example Program
Consider the following complete Go program, which demonstrates creating a buffered channel for integers, sending two values (10 and 11) into it, closing the channel, and then receiving the values:Running the Program
You can run the above program using the following command:Explanation of the Output
- 10 true: The first output indicates that the value 10 was received from the open channel.
- 11 true: After the channel is closed, the remaining buffered value 11 is still available, resulting in a true status.
- 0 false: A final receive operation on a closed and empty channel returns the zero value for the type (here, 0 for int) along with false, indicating that no further values can be received.
Attempting to send data to a closed channel will cause a runtime panic. Always ensure you close a channel only when you’re certain no further data will be transmitted.