4 ms·
Both iterator examples have alternatives where you don't need a for loop. Try using for_each and you can collect an iterator of results into a single Result<_>
by dpbriggs 4y ago
Both iterator examples have alternatives where you don't need a for loop. Try using for_each and you can collect an iterator of results into a single Result<_> you can then early return with.
Both of those are made cleaner by not using for loops.
- cormacrelf 4y agoFor clarity it is called try_for_each: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.try_for_each https://doc.rust-lang.org/stable/std/iter/trait.Iterator.htm... The ? operator can be used both inside and after it like so: iter.try_for_each(|_| { … xxx?; … })?;
- vlovich123 4y agoThe author is right that this doesn’t compose though. What happens when the closure is async? Do we need an tier.async_for_each? What if we want both? Does the library author need to provide a try_async_for_each? This is a combinatorial explosion for each additional effect added which means it’s not composable. https://blog.rust-lang.org/inside-rust/2022/07/27/keyword-generics.html https://blog.rust-lang.org/inside-rust/2022/07/27/keyword-ge...
- dpbriggs 4y agoOh neat, I didn't know that existed. That's a combination of what I was trying to say above. If your for loop body is infallible then for_each is good enough. If you're trying to 'collect' some iterator into some data structure T, you can collect into Result<T, _> and question mark on that.
- seanhunter 4y agoNot a rust person, but both of the for loop examples seem extremely contrived. If you're going to do .filter , presumably you can do a .map or something and just supply a small lambda which does what was in the body of the for loop in the example? Alternatively you could just do the filter part using an if statement in the for loop. Either of those syntaxes would be much more straightforward than doing half of one and half of the other. It just doesn't make sense to do that and point at the result as being unergonomic. Secondly the fact that for and for_each have different characteristics is as someone else has pointed out fundamentally just that blocks and functions are different things. ie it breaks the author's mental model because their mental model is just wrong.