In C, a for loop has an optional increment section which I sometimes miss in Rust:
for (uint i = 0; i < max; i = step_function(i, j, k)) {
/* many lines of code! */
}
This could be written in Rust as:
let mut i: u32 = 0;
while (i < max) {
//
// many lines of code!
//
i = step_function(i, j, k);
}
... however this will introduce bugs if continue
exists somewhere in the "many lines of code". My personal preference is also to keep the increment at the top of the loop.
Without creating a special iterator to handle this, is there a way to loop that matches C style more closely, accounting for both issues mentioned?
By "special iterator", I mean not having to define an iterator type and methods outside the for loop.
While it may seem like an artificial requirement, having to define an iterator for a single use - adds some overhead both in reading and writing the code.
Although @kennytm's answer shows how a reusable StepByFn
iterator could work, using closures adds some constraints to the code that wouldn't exist otherwise.