by laureny · 13y ago · 0 comments
Modern languages should all support some form of foreach, e.g. Java:
for (Customer c : customers) { ... } // no iterator
C#, Scala and many others get this right as well. Go doesn't.And, this:
close(ch) // Remember to close or the loop never ends!
Seriously?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:
for (Entry<String, String> entry: map.entrySet()) { ... }
Go exposes too many implementation details to my taste.But the Java 'foreach' loop is just syntactic sugar around iterators, and your fragment will expand to:
for (Iterator<Entry<String, String>> iter = map.entrySet().iterator(); iter.hasNext(); ) {
Entry<String, String> entry = iter.next();
...
}
For this reason, the foreach-loop requires that the object that you loop over implements the Iterable interface.To be honest, every release of Go feels more and more like Java anyway. I won't be surprised when Go eventually ends up being a JVM-less Java in the same way a new OS will end up being unix. After all, "Those who don't understand Unix are condemned to reinvent it, poorly." – Henry Spencer
Maybe Java is the same way? Not to say unix (plan 9?) or java (scala?) are perfect, but there is a reason they are popular.
for c := range customers { }
So you at least need to write them for your own data structures so that the code knows how to navigate them.
But yeah, Go still needs a few improvements to be usable as a language for generic programming.