How can I iterate over a range in Rust with a step other than 1? I'm coming from a C++ background so I'd like to do something like
for(auto i = 0; i <= n; i+=2) {
//...
}
In Rust I need to use the range
function, and it doesn't seem like there is a third argument available for having a custom step. How can I accomplish this?
If you are stepping by something predefined, and small like 2, you may wish to use the iterator to step manually. e.g.:
You could even use this to step by an arbitrary amount (although this is definitely getting longer and harder to digest):
Use the num crate with range_step
range_step_inclusive
andrange_step
are long gone.As of Rust 1.28,
Iterator::step_by
is stable:It seems to me that until the
.step_by
method is made stable, one can easily accomplish what you want with anIterator
(which is whatRange
s really are anyway):If one needs to iterate multiple ranges of different types, the code can be made generic as follows:
I'll leave it to you to eliminate the upper bounds check to create an open ended structure if an infinite loop is required...
Advantages of this approach is that is works with
for
sugaring and will continue to work even when unstable features become usable; also, unlike the de-sugared approach using the standardRange
s, it doesn't lose efficiency by multiple.next()
calls. Disadvantages are that it takes a few lines of code to set up the iterator so may only be worth it for code that has a lot of loops.You'd write your C++ code:
...in Rust like so:
I think the Rust version is more readable too.