|
|
|
|
|
by ewencp
4662 days ago
|
|
You need them because the examples are intentionally simplified. Even a data structure as simple as a dictionary has a useful variety of iterators: over keys, over values, and in some languages, over (key,value) tuples. Explicit iterators are really only noise for the "natural" iterator, i.e. in order iteration over an array. I agree that having it hidden by a language feature is nice, but somewhere there is an iterator -- the class that supports that iteration must at least specify how it's accomplished. I would prefer if there were an easy way to integrate with the range keyword in Go. EDIT: Adding to reply to some added comments. The close() one in particular really threw me. It makes sense in terms of how channels work, but is really unfortunate. When I first saw the channel-based approach, I thought it was a neat solution. But then I found all the problems with it (including the best example I could find of it online missing that close(), which is why I pointed it out!). I think Go is close to getting it right if they would do what I mention at the end of the article: provide a way to hook into the range keyword. |
|
Not really, they are really noise in a lot of situations. Right now, I can only think of one case where they are necessary: lazy traversal. Either the collection is huge or each element is expensive to materialize, so you want to do that one at a time. Iterators are perfect for this.
They are unnecessary in all other cases. For example, for your (key, value) example:
Go exposes too many implementation details to my taste.