In this lesson, you’ll learn how to properly close a channel in Go and understand the behavior of channels upon closure. Closing a channel signals that no further data will be sent, which is particularly useful when you’ve transmitted all necessary data. When receiving a value from a channel, you can check if the channel is closed by capturing a second boolean return value in the receive expression. For example:Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
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.