How do you make a range in Rust?

mcandre picture mcandre · Feb 14, 2012 · Viewed 27.4k times · Source

The docs don't say how, and the tutorial completely ignores for loops.

Answer

nejucomo picture nejucomo · Oct 2, 2013

As of 1.0, for loops work with values of types with the Iterator trait.

The book describes this technique in chapter 3.5 and chapter 13.2.

If you are interested in how for loops operate, see the described syntactic sugar here:

http://doc.rust-lang.org/std/iter/index.html

Example:

fn main() {
    let strs = ["red", "green", "blue"];

    for sptr in strs.iter() {
        println!("{}", sptr);
    }
}

(Playground)

If you just want to iterate over a range of numbers, as in C's for loops, you can create a numeric range with the a..b syntax:

for i in 0..3 {
    println!("{}", i);
}

If you need both, the index and the element from an array, the idiomatic way to get that is with the Iterator::enumerate method:

fn main() {
    let strs = ["red", "green", "blue"];

    for (i, s) in strs.iter().enumerate() {
        println!("String #{} is {}", i, s);
    }
}

Notes:

  • The loop items are borrowed references to the iteratee elements. In this case, the elements of strs have type &'static str - they are borrowed pointers to static strings. This means sptr has type &&'static str so we dereference it as *sptr. An alternative form which I prefer is:

    for &s in strs.iter() {
        println!("{}", s);
    }