3 ms·
> This is just so goofy. Who writes Rust like this? Wouldn't everyone write: something.iter_mut().…().for_each(|(i, x)|) { … }) No. As a user for just short of
by chrismorgan 4y ago
> This is just so goofy. Who writes Rust like this? Wouldn't everyone write: something.iter_mut().…().for_each(|(i, x)|) { … })
No. As a user for just short of a decade, I have probably used .for_each() less than a dozen times in total (grep over the current state of most of the code I’ve ever written: three matches). I know it’s there, but it doesn’t often feel right, and I have certainly regularly used for loops where closure capture rules mean that I couldn’t have used .for_each(), which is strictly less expressive. Perhaps if I had come from a language like Ruby I might use it more, but I came more from Python and JavaScript.
I don’t think the article showed a good formatting, however; I’d write it more like this:
for (i, x) in something
.iter_mut()
.filter(|| {...})
.enumerate()
{
*x = (*x) * i;
}
- mustache_kimono 4y ago> I know it’s there, but it doesn’t often feel right, and I have certainly regularly used for loops where closure capture rules mean that I couldn’t have used .for_each(), which is strictly less expressive. I think this is fine. I think Rust's strength is as a multi-paradigm language. I would say for this specific code, a for_each() makes more sense than the alternatives (on the margin), but for more complex use cases, where something like a try_for_each() might be used, where you may need to return 3 different error types, which for some reason one type can't be easily coerced out of the closure, a for loop makes tons of sense. But I think that's a 5% use case, and in the other 95% of cases the iterator approach is to be preferred. For many sound technical reasons, as well as for more squishy code readability reasons (maps and folds and filters are simply more readable to my eye). Again I strictly don't have a problem with anything in your comment, or anyone using for loops, but if I was writing your for loop and my concern was the author's re: pretty syntax, I'd write it as: let y_iter = some.iter().built().up().like().this(); for x in y_iter { ... }