A bit of a dumb question but should channels be explicitly closed after you’re done using them, or is that something the GC will take care of? My instincts are telling me yes but I also do frequently see code that doesn’t explicitly close any of the channels it creates.
There’s no need to explicitly close a channel. It can just go out of scope and the GC will clean it up. Channels do not hold any resources and if there are no references to it left, it means nobody is waiting on it and nobody can send anything. So technically it can be considered factually closed because there’s no way anything is going to be sent through it at that point.
The main reason to close them is that if you have any waiters then they won’t get stuck forever. So it is good practice to close them just to avoid having zombie fibers - and it is a lot easier to track down a crash than a silent no-resume.
I see thanks!
I believe I read somewhere that you are still able to read one value from a closed channel before it errors.
So when you close a (buffered) channel and the receiver fiber has stopped before it could read the last value, does that mean the memory will be kept around forever? Or is that also something the GC will take care of if nothing else references the channel.
I’d assume you’d be able to read all the values that were written to it, but that you get an error when it is empty and try to read.
Yes, reading from a closed channel only starts failing when its buffer is empty (i.e. graceful close).
A channel won’t be collected if any producer or consumer still references it, but it will be collected once nothing references it anymore along with its buffer, regardless if the buffer is empty or not.