For in Rust

Rust provides several ways to write loops. Let’s explore the different types of loops available.

fn main() {
    // The most basic type, with a single condition.
    let mut i = 1;
    while i <= 3 {
        println!("{}", i);
        i += 1;
    }

    // A classic C-style for loop.
    for j in 0..3 {
        println!("{}", j);
    }

    // Iterating over a range of numbers.
    for i in 0..3 {
        println!("range {}", i);
    }

    // An infinite loop that breaks.
    loop {
        println!("loop");
        break;
    }

    // Using continue to skip iterations.
    for n in 0..6 {
        if n % 2 == 0 {
            continue;
        }
        println!("{}", n);
    }
}

To run the program:

$ rustc for.rs
$ ./for
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Rust, the for loop is primarily used for iterating over collections or ranges. The while loop is used when you need a loop with a single condition. The loop keyword creates an infinite loop that you can break out of.

The continue statement works similarly to other languages, skipping to the next iteration of the loop.

We’ll see more loop forms later when we look at iterators, closures, and other data structures.