Is it OK to leave a channel open?

后端 未结 5 1162
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 01:29

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?



        
5条回答
  •  日久生厌
    2020-11-28 02:14

    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.)

提交回复
热议问题