It would be nice to be able to do this:
let count = 15;
loop count {
println!("{}", count);
}
would loop 15 times.
Whats wrong with
for _ in 0..15 {
println!("{}", count);
}
@KrishnaSannasi
Whats wrong with
for _ in 0..15 { println!("{}", count); }
These have different semantic meanings. for _ in 0..15 is the same as for _ in 1234..1249. loop 15 makes it clear that it is just being repeated x times.
Ok, how often do you actually need to repeat a thing a fixed number of times? I don't see the point of this extensions, especially when for _ in 0..$count { ... } does the job and is very clear. Keeping 0 as the lower bound and using _ to ignore the iterator items makes it clear that you want to do is loop a fixed number of times.
Is there precedence for this sort of loop in other languages? I can't think of any of the top of my head.
Extending loop to do this doesn't seem to be very productive, or add very much. In fact it detracts from the meaning of loop a bit. There is utility in knowing that loop implies some strange control flow (which can't be modeled by for or while). So, adding loop $count { ... }, while minor on it's own, does somewhat break this rule. (Although, I have seen other proposals to do exactly this, so there may be some merit to adding it)
What values can you put in $count? Any integer? Does it have to be compile time known? Can we use custom types in $count? If so, what trait controls the behavior?
Finally, there is the concern of how to handle break in this loop.
Right now, you can do this.
assert_eq!(1, loop { break 1 });
I would expect loop $count { break 1 } to be a compiler error, because the loop could end gracefully similarly to how for _ in 0..$count { break 1 } is an error.
Are there any parsing ambiguities with this? For example
loop { return } { }
could parse as
loop $count { } // where $count = { return 10 }
or
loop { return } // normal infinite loop that is terminated by a return
{ } // unreachable block
for _ in 0 .. nb is pretty clear to me and already small enough. Furthermore, loop constructs have contracts:
for is often used for deterministic looping — i.e. when you know at most how many times you’ll iterate.while is used to loop while a condition is held true, which is already different from the previous construct.loop is used to loop without even knowing the condition and requires a break.What you describe falls in the first family of constructs and I suggest you simply add macro for it or just an Iterator type, such as:
for _ in times(3) {
}
Or,
times(3, || {
});
It seems unlikely that we would support this given that we also closed https://github.com/rust-lang/rfcs/pull/2617. There also doesn't seem to be any strong support or motivation. Closing therefore.
Most helpful comment
Whats wrong with