What happens when a channel goes out of scope

What happens when a channel goes out of scope


here is an example.

main() calls func1()
func1() declares a channel, starts a goroutine, and terminates.
goroutine writes to the channel (without blocking as the channel is buffered)
and terminates too.

func main() {
	time.Sleep(1 * time.Second)

func func1() {
	ch := make(chan int, 1)
	go func() {
		ch <- 1

The channel goes out of scope and there are no references to it anymore. Will it
be garbage collected? Is there anything else to the channel that needs to be
done? Is this code correct?


Channels are garbage collected just like everything else. There are plenty of references on the web that state that closing a channel is not necessary for it to be collected.

Thank you Jeff.

It turns out that my confusion was due to the fact that I’m leaving the channel
with a data item in it.

The data in the channel do not implicitly reference the channel, so the channel should be collected independent of its contents, unless, of course the data are structs that do reference the channel. In that case, mutual references are not a problem for garbage collection. However, the data cannot be collected if an uncollected channel still references them.

Oh, that’s a good point to bear in mind.

thanks, igor