Is it OK to leave a Go channel open forever (never close the channel) if I never check for its state? Will it lead to memory leaks? Is the following code OK?
func (requestCh chan<- Request) GetResponse(data RequestData) Response { reply := make(chan Response) requestCh <- Request{data: data, replyCh: reply} return <-reply }
The Channel Closing Principle One general principle of using Go channels is don't close a channel from the receiver side and don't close a channel if the channel has multiple concurrent senders. In other words, we should only close a channel in a sender goroutine if the sender is the only sender of the channel.
Closing a channel indicates that no more values will be sent on it. This can be useful to communicate completion to the channel's receivers. In this example we'll use a jobs channel to communicate work to be done from the main() goroutine to a worker goroutine.
It's OK to leave a Go channel open forever and never close it. When the channel is no longer used, it will be garbage collected.
Note that it is only necessary to close a channel if the receiver is looking for a close. Closing the channel is a control signal on the channel indicating that no more data follows.
Design Question: Channel Closing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With