For expressions

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?

How would that work in no_std programs where Vec doesn’t exist?

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?

People would argue a .map() suffices.

1 Like

Sorry I should have been clearer, it would be returning an IntoIterator ( https://doc.rust-lang.org/std/iter/trait.IntoIterator.html ) - the same way that collect() currently works.

You probably meant FromIterator.

1 Like

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.

See this proposal, for (in my opinion) better alternative regarding return value of for loop:

Also your proposal looks too similar to map + collect, so I think it will be redundant.

1 Like

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.