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