4 ms·
Here's a rough implementation of iterators using channels that I was experimenting with. It needs some syntactic sugar to do proper cleanup of the go routine i
by thwarted 2y ago
Here's a rough implementation of iterators using channels that I was experimenting with. It needs some syntactic sugar to do proper cleanup of the go routine if the loop exits early; probably the iterator function needs to return a func that closes the channel called after the loop, and some error handling/closed channel checking.
https://gist.github.com/thwarted/a6e5e7ca5ce552311a7d5ece13d298ac https://gist.github.com/thwarted/a6e5e7ca5ce552311a7d5ece13d...
- tapirl 2y agoWhat is meaningfulness of the two `yield` functions? I mean why not expand/inline them. To use channels as iterators efficiently, we need find a way to let the functions creating the channels return without creating new goroutines.
- thwarted 2y agoThe yield functions only exist as syntactic sugar to make it look like iterators in other languages and to make it clear where the value emission point is (I had mentioned this in tweets and skeets when I was originally working on this, if didn't make it into the gist). An unbuffered channel is really a scheduler abstraction. Consuming from an unbuffered channel blocks, the thread can enter and immediately begin executing the go routine that was blocking on producing. The go routine is acting like a closure around the channel state. I had some further experiments interleaving these iterators, but didn't clean it up at the time before I had sufficiently convinced myself it was possible and I got distracted with other things.
- tapirl 2y agoThe idea listens promising. It is more intuitive than the current design.