This idea is useful and harmonize with expression based foundation of Rust:
While completely unnecessary and probably a bad idea for 1.0, it would be kind of nice if one could return a value (other than ()) from a loop (I apologize if this has already been discussed). For example: let maybe_item = for item in haystack { ...
Reading time: 3 mins 🕑
Likes: 13 ❤
rust-lang:master
← ftxqxd:loop-else
opened 01:05AM - 04 Oct 14 UTC
Extend `for`, `loop`, and `while` loops to allow them to return values other tha… n `()`:
- add an optional `else` clause that is evaluated if the loop ended without
using `break`;
- add an optional expression parameter to `break` expressions to break out of
a loop with a value.
[Rendered view](https://github.com/P1start/rfcs/blob/loop-else/text/0000-loops-returning-values.md)
(See also [this discuss thread](http://discuss.rust-lang.org/t/allow-loops-to-return-values-other-than/567).)
opened 10:28PM - 10 Mar 15 UTC
closed 09:26PM - 08 Apr 17 UTC
T-lang
Extend for, loop, and while loops to allow them to return values other than ():
… - add an optional else clause that is evaluated if the loop ended without using break;
- add an optional expression parameter to break expressions to break out of a loop with a value.
Proposed in #352
Some discussion of future-proofing is available in #955
I've found a simple alternative approach to return values outside the loop:
fn main() {
let loop_result = (move || loop {
return 32i32;
})();
println!("{:?}", loop_result);
}
Sounds like moved loop (it's not necessary in this case). Also I can use try!
macro with this approach.
How much overhead such loops wrapping has?
Maybe are there alternative ways to have a infinite loop which runs a long sequence that can be broken anytime with Err which I want to use for silently error processing (without panic)?