What is a stable way to iterate over a range with a custom step?


How should I go if I want to iterate with a custom step in Rust? Essentially something like the C/C++

for (int i = 0; i < n; i += 2) {


I've already tried using range_step_inclusive

use std::iter::range_step_inclusive;
for i in range_step_inclusive(0, n, 2) {
    println!("i: {}", i);

But it seems like it isn't available in Rust 1.1

error: unresolved import `std::iter::range_step_inclusive`. There is no `range_step_inclusive` in `std::iter`

What would be an alternative? Possibly the idiomatic way for creating custom ranges.

As of Rust 1.1

You can always write it out the old-fashioned way:

fn main() {
    let mut i = 0;
    while i < 100 {
        println!("i: {}", i);
        i += 2;

Which can then be abstracted:

use std::ops::Add;

fn step_by<T, F>(start: T, end_exclusive: T, step: T, mut body: F)
    where T: Add<Output = T> + PartialOrd + Copy,
          F: FnMut(T)
    let mut i = start;
    while i < end_exclusive {
        i = i + step;

fn main() {
    step_by(0, 100, 2, |i| {
        println!("i: {}", i);

Interesting historical side note, I believe that originally all the looping was done with closures like this, before iterators became extremely prevalent.