Should 'for' expressions be able to return an expression other than '()'?
For example, the following doesn't compile:
let inputs = vec![1,2,3];
let results : Vec<_> = for a in inputs {
println!("I'm a statement");
a + 1
};
assert_eq!(results, vec![2,3,4])
Given how functions and matches return expressions, to me it feels like the above might naturally fit in. Loops and collections tend to go hand in hand - to me this feels natural. Has this been discussed before?
A nested for loop could turn itself into a Vec<Vec<_>>. I know many will prefer a more functional style than for loops, but this feels like rounding off what already exists. One might reasonably expect the above to work given a working knowledge of rust. Keen to hear others views... do people feel this is worth taking forward to an RFC or is there a down side that I have overlooked?
I'd say the bar for adding new language features/syntax should be extremely high, and this doesn't cut it IMHO - there's not enough, if any, utility. Do you have a compelling use case?
Sorry I should have been clearer, it would be returning an IntoIterator ( IntoIterator in std::iter - Rust ) - the same way that collect() currently works.
I don't think that's possible. How would break work?
Edit: Also, that would involve silently rewriting for loops into generators, taking them from eagerly evaluated to lazily evaluated, and probably changing borrow semantics.
Thanks vitalyd, your right. I totally agree that there's a bar for language changes - after all how else are RLS and intellij rust going to keep up. I'm more than happy that people decide not to do it on grounds of language stability.
I proposed it on the grounds that it makes the language a bit more regular. There's talk ( https://github.com/rust-lang/rfcs/issues/961 ) on returning a value from a loop, but to me a loop is an iteration of something - it would naturally return something iterable.
@newpavlov - that looks lovely - that's exactly what I was really asking for, it gets my vote.