What happens when a channel goes out of scope

What happens when a channel goes out of scope

Hi;

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() {
	func1()
	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?

Thanks,
igor

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.

1 Like

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

thanks, igor

In my code, I have a function startProcessing() that initializes a buffered channel, launches a goroutine to process some data, and then returns the channel. The goroutine performs its tasks and writes to the channel as expected. However, after calling startProcessing() , when attempting to receive from the channel in the main function, it seems that the data is not being transmitted correctly, and the channel appears to be empty.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.