← Back to list

Mastering Loops in Rust: A Comprehensive Guide to For, While, and Loop (Tutorial 16/100)

Introduction

Giorgio Martinez in Towards Dev · 2024-07-04 16:02 · 13 claps · 3.1 min read paywalled
#rust #rust-programming-language #rust-loop #coding #coding-in-rust
Open on Medium ↗
Wiki topics: 💻 · Programming

Mastering Loops in Rust: A Comprehensive Guide to For, While, and Loop (Tutorial 16/100)

Introduction

Rust is a modern programming language that prioritizes performance, reliability, and productivity. One of the essential concepts in programming, including Rust, is looping. Loops allow developers to execute a block of code repeatedly until a specific condition is met. In Rust, there are three primary loop constructs: for, while, and loop. This article will delve into each loop type, providing examples and best practices to help you master loops in Rust.

For Loop

The for loop is used to iterate over a collection of items, such as arrays, vectors, or strings. The syntax for a for loop in Rust is as follows:

for item in collection {
    // code to execute for each item
}

Here’s an example of using a for loop to iterate over an array:

fn main() {
    let arr = [1, 2, 3, 4, 5];
    for num in &arr {
            println!("{}", num);
    }
}

In this example, the for loop iterates over the array arr, and the variable num holds the current element's value. The & symbol is used to create a reference to the array, avoiding unnecessary copying.

While Loop

The while loop is used to execute a block of code repeatedly as long as a specified condition is true. The syntax for a while loop in Rust is as follows:

while condition {
    // code to execute while the condition is true
}

Here’s an example of using a while loop to print the numbers from 1 to 5:

fn main() {
    let mut num = 1;
    while num <= 5 {
            println!("{}", num);
            num += 1;
        }
    }

In this example, the while loop continues to execute as long as num is less than or equal to 5. The variable num is incremented by 1 at the end of each iteration.

Loop Keyword

The loop keyword is used to create an infinite loop that executes a block of code repeatedly. To stop or skip iterations, you can use the break and continue keywords. The syntax for a loop in Rust is as follows:

loop {
    // code to execute indefinitely
}

Here’s an example of using a loop to print the numbers from 1 to 5:

fn main() {
    let mut num = 1;
    loop {
            if num > 5 {
                break;
            }
            println!("{}", num);
            num += 1;
        }
    }

In this example, the loop continues indefinitely, but the break statement is used to exit the loop when num is greater than 5.

Nested Loops

Loops can be nested inside other loops, allowing for more complex iterations. Here’s an example of using nested loops to print a multiplication table:

fn main() {
    for i in 1..=10 {
        for j in 1..=10 {
            println!("{} * {} = {}", i, j, i * j);
        }
    }
}

In this example, the outer for loop iterates over the values of i from 1 to 10, while the inner for loop iterates over the values of j from 1 to 10. The multiplication result is printed for each combination of i and j.

Loop Labels

Loop labels allow you to specify a name for a loop, which can be useful when working with nested loops or breaking out of an outer loop. Here’s an example of using loop labels:

fn main() {
    'outer: for i in 1..=5 {
        for j in 1..=5 {
            if i + j == 8 {
                continue 'outer;
            }
            println!("i: {}, j: {}", i, j);
        }
    }
}

In this example, the 'outer label is assigned to the outer for loop. When the sum of i and j equals 8, the continue statement skips the current iteration of the outer loop.

Best Practices

  1. Use for loops when iterating over collections with a known number of items.
  2. Use while loops when the number of iterations is unknown or dependent on a specific condition.
  3. Use loop with break and continue for more granular control over loop iterations.
  4. Use loop labels to improve readability and control flow when working with nested loops.

Conclusion

In this article, we have explored the three primary loop constructs in Rust: for, while, and loop. We've discussed their syntax, usage, and best practices, along with examples to demonstrate their functionality. Understanding loops is crucial for any Rust developer, as they form the backbone of many algorithms and data processing tasks. With this knowledge, you'll be well-equipped to tackle more complex programming challenges in Rust.

References

  1. The Rust Programming Language Book — Loops
  2. Rust by Example — Loops
  3. Rustlings — Loops

Follow me for more thought-provoking content. Stay tuned for what’s next.


메타데이터
post_id
d9ed3703a7ef
slug
mastering-loops-in-rust-a-comprehensive-guide-to-for-while-and-loop-tutorial-16-100-d9ed3703a7ef
url
https://towardsdev.com/mastering-loops-in-rust-a-comprehensive-guide-to-for-while-and-loop-tutorial-16-100-d9ed3703a7ef
canonical_url
https://towardsdev.com/mastering-loops-in-rust-a-comprehensive-guide-to-for-while-and-loop-tutorial-16-100-d9ed3703a7ef
author_url
https://medium.com/@giorgio.martinez1926
status
ok
fetched_at
2026-07-27 12:31:45