Rust: loops


2 min read

Play this article

Repetition With Loops

Rust has 3 kinds of loops - loop, while and for.

Loop syntax:

// for
let counter = [10, 20, 30, 40, 50];

for c in counter {
    println!("the value is: {c}");
// while
let mut counter = 0;
while counter != 3 {
    counter += 1;
// loop
let mut counter = 0;
let result = loop {
    counter += 1;
    if counter == 3 {
        break counter * 2; // break also acts as return

Loop Labels

break and continue by default apply to the innermost loop at the point when one of these keywords is called. You can use loop labels to change the behaviour and break out of another loop instead.

let mut count = 0;
'counting_up: loop {
    println!("count: {count}");
    let mut remaining = 10;
    count += 1;

    loop {
        println!("remaining: {remaining}");
        if count == 3 {
            break 'counting_up; // breaks out of the parent loop

        remaining -= 1;

iter() method

When discussing loops, iter() serves as a valuable tool, especially for types that implement the Iterator trait. The Vector is a prime example of such types. Using this method opens the door to a plethora of helper functions, simplifying many basic tasks. These helper functions can be categorized into two types:

  1. Immediate-return Functions: These return a value instantly, such as .last(), .min(), and others.

  2. Collectible Methods: These perform specific actions on the iterable items, but to obtain the final result as a new vector, one must call the .collect() method at the end. When using these collectible methods, it's essential to specify the type of vector you expect to return while initialising the variable that will store it.

Moreover, it's worth noting that you can chain multiple collectible methods together.

let my_iter = vec![1, 2, 3, 4, 5];

let stacked_collectible: Vec<_> = my_iter.iter().take(3).filter(|&&n| n >= 2).collect(); // collectible
let last = my_iter.iter().last(); // immediate return

println!("{:?}", stacked_collectible);
println!("{:?}", last);