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

> Agreed, but I think people make too big a deal about iterators.

I may just have more time to dick around, but I've been forcing myself to write everything as an iterator in Rust (instead of a for loop) just to learn the paradigm and, honestly, it's been pretty great.

First, there is a performance impact. You may think this would be small, but, in my experience, it can be relatively large. There must be several reasons of which I am ignorant, but they probably include mutable no alias inside closures, bounds check elision, etc.

Second, there is a mutability advantage to just using filter/flatten/map/collect for 90% of your use cases.

Third, the more advanced iterator methods will cover the other 5-10% of your use cases, and will make your code much easier to read, once you understand how to use them (if you're trying to learning something/anything more complex at the same time, save your brain power!). I don't have a single traditional for loop in my personal projects.

My take on iterators is, for iterator/Rust beginners (like me!/perhaps not you) -- the best way to learn is to get it working as imperative code, and when you have the time, go back a rewrite as an iterator. In the beginning, it's super frustrating. But you'll get better and better and, after awhile, you'll much, much prefer writing as an iterator. You won't even think of using a for loop.



I mean, I definitely have tried to rewrite stuff as iterators even when it isn't convenient. I only got to that working example by dedicating a few hours with the good people on the Rust Discord trying to make it work (a lot of seasoned Rustaceans also weren't able to get it working, it was a collaborative effort that took a fair amount of time and rhapsodizing). And even then, the result is pretty ugly (I don't think many seasoned Rustaceans would call it "idiomatic" or advise the first version over the second).


Agreed. Your example is a pretty pathological case, but yeah.




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

Search: