News for hackers. Stuff that matters.
Re:Iterator patterns in Go by Laremere on Sunday September 08, 2013 @12:21AM (#6347819)
It's very important when looking at the channel method to realise that goroutines are NOT garbage collected. If there is any chance of the loop calling break or panicking, there is a chance of leaking goroutines. Since you might not know how your code is going to be used, this is an issue. A possible solution is to use two channels, the items channel and a fail channel. Whenever your iterator sends, it needs to use a select which either sends the item on the channel, or receives from a fail channel (in which case it exits the function.) I think while the channel method looks nice because of Go's special treatment of it's basic types (for better or worse,) it's not practically the best answer you should be using in your code.
Re:Iterator patterns in Go by ewencp on Sunday September 08, 2013 @12:26AM (#6347828)
I mentioned this pitfall, but didn't show how to solve it. I haven't seen a complete example yet and didn't take the time to work out the details yet. I'm less concerned about complexity in the iterator implementation, but handling this correctly also seemed to require changing the caller code since it needs to send something on the fail channel. Then the onus is on the caller to remember to do so, which is just as bad as having to remember not to call break.

Of course, whether this is a real issue or not also depends on whether you're writing internal or external APIs. There are lots of other ways to generate uncollectible garbage too...

Re:Iterator patterns in Go by cmccabe on Sunday September 08, 2013 @12:52AM (#6347870)
Use "defer close(ch)". If there is a break or a panic, the channel will be closed.
Re:Iterator patterns in Go by Laremere on Sunday September 08, 2013 @01:21AM (#6347905)
If there is a break or panic in the iterator, not the loop using the iterator. If the loop using the iterator closes the channel, the program will crash.
Re:Iterator patterns in Go by cmccabe on Sunday September 08, 2013 @02:06AM (#6347991)
The sender is supposed to close the channel to signify to the receiver that there is no more data to be sent. The receiver is not supposed to close the channel. (You could hack around this by recovering from the panic, but this is bad style.)

https://groups.google.com/forum/#!topic/golang-nuts/RmfHSHE9...

Note that there is no requirement that you close channels-- they aren't like file descriptors. They will be garbage collected after they're no longer needed.

goroutines, on the other hand, will stick around unless you clean them up. goroutines aren't iterators, and you shouldn't use them as iterators. They're more analogous to threads.