Loops

Loops are used to execute a block of code multiple times based on a condition. There are a few ways to create loops in Rust:

Learn Rust by Practice

Master Rust through hands-on coding exercises and real-world examples.

Using loop

You can create a loop using the loop keyword. This will keep executing the block of code until you explicitly tell it to stop using the break keyword.

fn main() {
    loop {
      println!("Hello, World!");
    }
}

In the example above, the code will keep printing Hello, World! forever because we are not breaking out of the loop. In order to break out of the loop, you can use the break keyword.

fn main() {
    let mut counter = 0;
 
    loop {
        println!("{}. Hello, World!", counter + 1);
 
        counter += 1;
 
        if counter == 10 {
            break;
        }
    }
}

The code above will continuously print Hello, World! and increment the value of counter by 1. When the value of counter reaches 10, the loop will break and the program will exit.

Loop with break Loop with break

Returning a value from a loop

Loops are also expressions in Rust, you can return a value from a loop using the break keyword. Here's an example:

fn main() {
    let mut counter = 0;
 
    let result = loop {
        counter += 1;
 
        if counter == 10 {
            break counter * 2;
        }
    };
 
    println!("The result is: {}", result);
}

In the example above, we are returning the value of counter * 2 when the value of counter reaches 10. The value of result will be 20.

Loop return Loop return

Skipping an iteration

Sometimes you might want to skip an iteration in a loop based on a condition. You can skip an iteration in a loop using the continue keyword. Here's an example:

fn main() {
    let mut counter = 0;
 
    loop {
        counter += 1;
 
        if counter % 2 == 0 {
            continue;
        }
 
        if counter > 9 {
            break;
        }
 
        println!("The number is: {}", counter);
    }
}

In the code above, we are skipping an iteration when the value of counter is even. The continue keyword will skip the rest of the code in the loop and move to the next iteration.

Loop continue Loop continue

Loop labels

Sometimes when you have multiple nested loops, what the break will do is quite ambiguous, it only breaks the innermost loop. But what if we want to break out of the outer loop? To specify which loop you want to break out of a specific loop, you can label your loops and then use the label with the break keyword to break out of that loop.

Here's an example:

fn main() {
    let mut outer_counter = 0;
    'outer: loop {
        let mut inner_counter = 0;
        'inner: loop {
            println!(
                "Outer loop: {}, Inner loop: {}",
                outer_counter, inner_counter
            );
            if inner_counter == 5 {
                break 'inner; // Exits the inner loop
            }
            if outer_counter == 2 {
                break 'outer; // Exits the outer loop
            }
            inner_counter += 1;
        }
        outer_counter += 1;
    }
}

In the example above, we have two nested loops. The outer loop is labeled as 'outer and the inner loop is labeled as 'inner. We are using the labels with the break keyword to break out of the loops. When the value of inner_counter reaches 5, the inner loop will break and when the value of outer_counter reaches 2, the outer loop will break.

Loop with label Loop with label

While loops

Rust let's us create loops using the while keyword. The while loop accepts a bool value as a condition and will keep executing the block of code until the condition is false.

fn main() {
    let mut counter = 0;
 
    while counter < 10 {
        println!("{}. Hello, World!", counter + 1);
        counter += 1;
    }
}

In the example above, the code will keep printing Hello, World! and increment the value of counter by 1 until the value of counter reaches 10.

While loops While loops

Notice that we did the same thing with while as we did with loop but the while loop is much more concise and readable, it's a good practice to use while when you know the condition beforehand.

For loops

For loops are a way to loop over a collection of items. In Rust, you can create a for loop using the for keyword.

fn main() {
    let numbers = [1, 2, 3, 4, 5];
 
    for number in numbers.iter() {
        println!("The number is: {}", number);
    }
}

In the example above, we are looping over an array of numbers and printing each number. The for loop will keep executing the block of code until it has looped over all the items in the collection.

For loops For loops

You can also use the for loop to loop over a range of numbers.

fn main() {
    for number in 1..5 {
        println!("The number is: {}", number);
    }
}

For range For range

You can also include the end value in the range by using ..=.

fn main() {
    for number in 1..=5 {
        println!("The number is: {}", number);
    }
}

For loop range include For loop range include

Skipping iterations and breaking out of loops are not exclusive to any type of loop, you can use continue and break in for and while loops as well.


In the next lesson, we will learn about pattern matching in Rust.