203

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?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177

5 Answers5

300

range_step_inclusive and range_step are long gone.

As of Rust 1.28, Iterator::step_by is stable:

fn main() {
    for x in (1..10).step_by(2) {
        println!("{}", x);
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Pill
  • 4,815
  • 1
  • 24
  • 26
  • 1
    cf. https://doc.rust-lang.org/core/ops/struct.Range.html#method.step_by and https://github.com/rust-lang/rust/issues/27741 – maxschlepzig May 07 '17 at 10:16
  • Note that this method will not support 64 bit step on machines with 32 bit size type. – user202729 Jun 03 '20 at 06:29
  • And if the step is half the value? – Leandro May 06 '21 at 21:24
  • 4
    Unfortunately, this doesn't nicely handle negative steps. Where you'd like to do, say, `(11..=1).step_by(-2)` (odd numbers counting down from 11 to 1, inclusive), you have to do `(1..12).step_by(2).rev()`, which is not quite as intuitive. – BallpointBen Dec 12 '21 at 06:13
16

It seems to me that until the .step_by method is made stable, one can easily accomplish what you want with an Iterator (which is what Ranges really are anyway):

struct SimpleStepRange(isize, isize, isize);  // start, end, and step

impl Iterator for SimpleStepRange {
    type Item = isize;

    #[inline]
    fn next(&mut self) -> Option<isize> {
        if self.0 < self.1 {
            let v = self.0;
            self.0 = v + self.2;
            Some(v)
        } else {
            None
        }
    }
}

fn main() {
    for i in SimpleStepRange(0, 10, 2) {
        println!("{}", i);
    }
}

If one needs to iterate multiple ranges of different types, the code can be made generic as follows:

use std::ops::Add;

struct StepRange<T>(T, T, T)
    where for<'a> &'a T: Add<&'a T, Output = T>,
          T: PartialOrd,
          T: Clone;

impl<T> Iterator for StepRange<T>
    where for<'a> &'a T: Add<&'a T, Output = T>,
          T: PartialOrd,
          T: Clone
{
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<T> {
        if self.0 < self.1 {
            let v = self.0.clone();
            self.0 = &v + &self.2;
            Some(v)
        } else {
            None
        }
    }
}

fn main() {
    for i in StepRange(0u64, 10u64, 2u64) {
        println!("{}", i);
    }
}

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 standard Ranges, 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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
GordonBGood
  • 3,467
  • 1
  • 37
  • 45
  • 1
    By adding another type, `U` to your second option you could use types that support addition with a different type and still yield a `T`. For instance time and duration come to mind. – Ryan May 14 '17 at 16:58
  • 1
    @Ryan, that seems like a good idea and should work, with the struct defined as follows: struct StepRange(T, T, U) where for<'a, 'b> &'a T: Add<&'b U, Output = T>, T: PartialOrd, T: Clone; which should allow different lifetimes for the input T and U types. – GordonBGood May 15 '17 at 02:22
6

You'd write your C++ code:

for (auto i = 0; i <= n; i += 2) {
    //...
}

...in Rust like so:

let mut i = 0;
while i <= n {
    // ...
    i += 2;
}

I think the Rust version is more readable too.

kmky
  • 783
  • 6
  • 17
  • Re: inserting "continue" in the loop, one would only do this inside a conditional branch even in the for structure, I think. If so, then I think it would be OK to increment inside the conditional branch in the while structure before "continue"-ing, and that it would then work as intended. Or am I overlooking something? – WDS Mar 04 '18 at 18:37
  • 1
    @WDS that's counterintuitive busywork to get a basic feature of the language, `continue`, to work properly. Though it can be done, this design encourages bugs. – Chai T. Rex Oct 12 '19 at 02:32
5

If you are stepping by something predefined, and small like 2, you may wish to use the iterator to step manually. e.g.:

let mut iter = 1..10;
loop {
    match iter.next() {
        Some(x) => {
            println!("{}", x);
        },
        None => break,
    }
    iter.next();
}

You could even use this to step by an arbitrary amount (although this is definitely getting longer and harder to digest):

let mut iter = 1..10;
let step = 4;
loop {
    match iter.next() {
        Some(x) => {
            println!("{}", x);
        },
        None => break,
    }
    for _ in 0..step-1 {
        iter.next();
    }
}
Leigh McCulloch
  • 1,886
  • 24
  • 23
5

Use the num crate with range_step

cambunctious
  • 8,391
  • 5
  • 34
  • 53