Rust Basics


Example

There are 4 looping constructs in Rust. All examples below produce the same output.

Infinite Loops

let mut x = 0;
loop {
    if x > 3 { break; }
    println!("{}", x);
    x += 1;
}

While Loops

let mut x = 0;
while x <= 3 {
    println!("{}", x);
    x += 1;
}

Also see: What is the difference between loop and while true?

Pattern-matched While Loops

These are sometimes known as while let loops for brevity.

let mut x = Some(0);
while let Some(v) = x {
    println!("{}", v);
    x = if v < 3 { Some(v + 1) }
        else     { None };
}

This is equivalent to a match inside a loop block:

let mut x = Some(0);
loop {
    match x {
        Some(v) => {
            println!("{}", v);
            x = if v < 3 { Some(v + 1) }
                else     { None };
        }
        _       => break,
    }
}

For Loops

In Rust, for loop can only be used with an "iterable" object (i.e. it should implement IntoIterator).

for x in 0..4 {
    println!("{}", x);
}

This is equivalent to the following snippet involving while let:

let mut iter = (0..4).into_iter();
while let Some(v) = iter.next() {
    println!("{}", v);
}

Note: 0..4 returns a Range object which already implements the Iterator trait. Therefore into_iter() is unnecessary, but is kept just to illustrate what for does. For an in-depth look, see the official docs on for Loops and IntoIterator.

Also see: Iterators