Returning Channels Golang

Because gen() fires off the channel population function as a goroutine;

go func() {
    for _, n := range nums {
        out <- n
    }
    close(out)
}()

and it blocks when the first value is sent on the out channel, because nothing is receiving yet (unbuffered channels block on sending until something receives on them), that goroutine doesn't end when the gen() function returns.

The receives from c in main()

fmt.Println(<-c)
...

then cause the goroutine started in gen() to keep populating the channel as the results are read out, and then finally main() returns when the goroutine returns, because there is nothing left to send on out, and nothing left to receive on c.

Also, the c := make(<-chan int) in main() is unnecessary as gen() creates a channel and returns it.

See Playground


out := make(chan int)

This is not a buffered channel, which means the out <- n will block until someone somewhere reads that channel (the fmt.Println(<-c) calls)
(See also "do golang channels maintain order")

So the return at the end of the gen() function doesn't mean the literal go func() is terminated (since it is still waiting for readers to consume the content of the out channel).

But main function getting out channel as return from gen() function.
How it is possible to get it after gen() is terminated?

The fact that gen() terminates has no effect on its returned value (the out channel): the goal of "gen()" is to "generate" that out channel.

main can use out (as the returned value of gen()) long after gen() terminates.

The literal go func within gen() still runs, even if gen() is terminated.


As noted by vagabond in the comments:

When gen() returns, there is still a reference to the out channel, which makes it not garbage collected.
It doesn't matter if the gen() has a go routine closure is using the channel.

When a channel is not used, the sender can close the channel explicitly.
And then the select for the channel will make the go routine to exit.
At last, everything will be cleared.

Tags:

Go