for in loop in Rust

for in

The for loop, or for-in loop, or iterator loop is used when we want to go over the elements of an iterator. This can be a fixed set of elements, but there can be also iterators where we don't know the number of elements up-front, and even iteartors that, at least theoretically, could go on indefinitely.

In this example we see two simple cases.

In the first case we iterate over the elements of a range.

In the second example we iterate over the elements of a vector.

The code

examples/for-loop/src/main.rs

fn main() {
    for i in 1..=3 {
        println!("{i}");
    }

    let animals = vec!["cat", "dog", "mouse"];
    for animal in animals {
        println!("{animal}");
    }   
}

The output

$ cargo -q run
1
2
3
cat
dog
mouse

Related Pages

loops in Rust
An almost infinite Fibonacci Iterator

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo