Is it OK to leave a channel open?

时光毁灭记忆、已成空白 提交于 2019-11-27 16:53:16

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

cizixs

Yes, it is ok to keep a channel open. As the go programming language book stated:

You needn't close every channel when you've finished with it. It's only necessary to close a channel when it is important to tell the receiving goroutines that all data have been sent. A channel that the garbage collector determinies to be unreachable will have its resources reclaimed whether or not it is closed. (Don't confuse this with the close operation for open files. It is important to call the Close method on every file when you've finished with it.)

Yes, it's OK to leave the channel open, and in fact it is typical. A channel being open does not constitute a reference to the channel object, and so does not keep it from being garbage collected.

Go is garbage collected, so you don't really have to 'free' anything.

There is possibility to close channels, but it's mostly used as - close(channel) - tell the goroutine (or main program) that nothing else will be sent on that channel.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!