Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Iterator callbacks, generators, or functors feel very un-Go-like. It's trying to force a Python or OCaml idiom on to Go. Basically, what you want is to implement a HasNext and a Next function and write a "for" loop. All you need is this:

  for ; iter.HasNext(); val = iter.Next() {
     // do stuff
  }
There's no reason to look down on the humble for loop. Complexity is a bad thing, usually.

Channels and goroutines are also a very Go-like way to process data. But APIs that return channels assume that the caller wants concurrency, so be sure that that's true.



Right, but you have to consider the complexity of the iterator implementation as well. Every time I implement iterators for non-trivial data structures in languages without generators I want to hit myself in the face for using that language.


> There's no reason to look down on the humble for loop. Complexity is a bad thing, usually.

No reason? By that you mean that there are no downsides? a hasNext()/next() often means that calling next() when there is no next element (hasNext() == false) will result in a nullpointer exception. That's fine if you always do a hasNext() check before calling next(), but people do make mistakes like that. You might say that something like a loop with a hasNext() conditional is simple enough, but on the other hand I'm not too fond of even using indexing loops in Java (for (int = i = 0; i < array.length; i++) {} ) if you only need to traverse the array one item at a time; you don't need the expressive power of indexing the array rather than simply iterating over it, and this increased power makes you more likely to introduce bugs (wrong initial value of index variable; wrong loop conditional; wrong increment operation: mixing up the indexing variables in a nested loops (the two similar-looking characters 'i' and 'j' are often used in that case). Even ignoring this argument, you might have to make a more complicated loop where the hasNext() or next() is a bit scattered due to some conditionals. (EDIT: since you are talking specifically about for loops this point may not be very relevant.)

I would say that a construct that doesn't encapsulate enough so that you might get a runtime error is in a way worse than a construct that encapsulates enough to guarantee that that mistake can not happen at runtime. It might not be overall worse, but it does have a downside, IMO.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: