Loops in Rust

Loops in Rust

Introduction

This is how loops in Rust are written.

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

This will keep on printing "Hello loop" till we stop it pressing Ctrl + C

So we need an exit condition.

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

Now Hello loop _ will be printed 10 times because we have a condition.

Hello loop 1
Hello loop 2
Hello loop 3
Hello loop 4
Hello loop 5
Hello loop 6
Hello loop 7
Hello loop 8
Hello loop 9
Hello loop 10

Return Values

Now Rust also allows us to return values from loops.

fn main() {
    let mut x = 0;
    let res = loop {
        x += 1;
        if x == 10 {
            break x * 10;
        }
    };
    println!("Loop result = {res}");
}

Here the loop is assigned to a variable res.

The loop closes when x = 10 and hence,

Loop result = 100

Nested Loops

In case we have loops within loops, those are called Nested loops.

Default break statements will break out from the innermost loop, unless loop name is specified. Below is an example:

fn main() {
    let mut x = 0;
    'outer_loop: loop {
        println!("x = {x}");
        x += 1;
        let mut y = 10;
        loop {
            println!("y = {y}");
            y -= 1;
            if y == 5 {
                break;
            }
            if  y == 7 {
                break 'outer_loop;
            }
        }
        if x == 10 {
            break;
        }
    }
}

Output:

x = 0
y = 10
y = 9
y = 8

While Loops

Since it's clear that loops must have a condition to gracefully exit, we have while loops that must be declared with a Condition.

fn main() {
    let mut x = 0;
    while x != 10 {
        x += 1;
        println!("x = {x}");
    }
}

Writing loops like this is much more simpler.

For Loops

One more thing that loops often expect is an initial and a final value based on which the exit Condition is written. In the above example it is the value of x

And this is when for loops come into the picture.

fn main() {
    for num in 1..10 {
        println!("{num}");
    }
}

Output:

0
1
2
3
4
5
6
7
8
9

So what is happening here.

First, the loop is looping from 0 to 10

Second, num is the value in each iteration

Hence we have the initial value = 0, final value = 10, and the exit condition, and that is num == 10

And we're printing the values of num

Looping Through Collections

Now loops can also be run through Collections. Below is an example:

fn main() {
    let nums = [10, 30, 20, 50, 40];
    for num in nums {
        println!("Current number = {num}");
    }
}

Output:

Current number = 10
Current number = 30
Current number = 20
Current number = 50
Current number = 40

Conclusion

That's all you need to know about loops in Rust for now. From the next Blog we'll get into more Rusty stuff. Cheers!