Rust Control Flow
Estimated reading: 3 minutes 51 views

🦀 Rust – Loops (General Overview): Iterate Safely and Efficiently

🧲 Introduction – Why Learn Loops in Rust?

Loops are essential for executing a block of code repeatedly. Rust offers three loop constructs—loop, while, and for—each designed with performance and safety in mind. Unlike traditional languages, Rust enforces strict bounds checking and ownership rules, making looping both efficient and bug-resistant.

🎯 In this guide, you’ll learn:

  • The three loop types in Rust: loop, while, and for
  • How and when to use each type
  • Loop control with break and continue
  • Code examples with outputs and line-by-line explanations

🔁 Infinite Loop Using loop

🔹 Code Example:

fn main() {
    let mut counter = 0;

    loop {
        counter += 1;
        println!("Counter: {}", counter);

        if counter == 3 {
            break;
        }
    }
}

🧠 Explanation:

  • loop starts an infinite loop.
  • counter += 1 increments the variable.
  • break exits the loop when counter == 3.

📤 Output:

Counter: 1
Counter: 2
Counter: 3

🔄 Conditional Loop Using while

🔹 Code Example:

fn main() {
    let mut num = 5;

    while num > 0 {
        println!("Countdown: {}", num);
        num -= 1;
    }
}

🧠 Explanation:

  • while checks the condition before each iteration.
  • num decreases until num > 0 is false.

📤 Output:

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1

🔂 For Loop with Range

🔹 Code Example:

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

🧠 Explanation:

  • 1..4 creates a range from 1 to 3 (exclusive of 4).
  • The loop iterates over values: 1, 2, 3.

📤 Output:

i = 1
i = 2
i = 3

📌 Use 1..=4 for inclusive range (includes 4).


💡 Loop with break Value

🔹 Code Example:

fn main() {
    let result = loop {
        let val = 10;
        break val * 2;
    };

    println!("Result: {}", result);
}

🧠 Explanation:

  • loop runs once here for demo.
  • break returns a value (20) from the loop into result.

📤 Output:

Result: 20

⏭️ Using continue in Loops

🔹 Code Example:

fn main() {
    for i in 1..=5 {
        if i % 2 == 0 {
            continue;
        }
        println!("Odd: {}", i);
    }
}

🧠 Explanation:

  • Skips even numbers using continue.
  • Only prints when i % 2 != 0.

📤 Output:

Odd: 1
Odd: 3
Odd: 5

🔄 Looping Over Collections with for

🔹 Code Example:

fn main() {
    let animals = ["dog", "cat", "fox"];

    for a in animals.iter() {
        println!("Animal: {}", a);
    }
}

🧠 Explanation:

  • .iter() provides an iterator over the array.
  • Each a borrows a value from the collection.

📤 Output:

Animal: dog
Animal: cat
Animal: fox

⚠️ Common Looping Mistakes

MistakeProblemFix
Forgetting break in loopInfinite loop (unintended)Use conditional break
Modifying collection while iteratingCauses borrow checker errorsUse .clone() or scoped mutation
Out-of-bounds indexingRuntime panicUse for with ranges or .iter()

📌 Summary – Recap & Next Steps

Rust provides flexible, safe, and efficient loop structures. Whether iterating fixed ranges, collections, or indefinitely, you’ll always benefit from type safety and ownership guarantees.

🔍 Key Takeaways:

  • loop is an infinite loop unless explicitly break-ed
  • while checks condition each time before looping
  • for is best for range-based or collection-based iteration
  • break and continue help manage loop control flow

⚙️ Up next: Explore each loop in-depth starting with Rust – While Loops.


❓FAQs


What’s the difference between loop, while, and for in Rust?
loop is infinite unless broken, while runs with a condition, and for iterates over a range or iterator.


Can a loop return a value in Rust?
✅ Yes. You can use break value; to exit a loop and return a value to the assigned variable.


How do I iterate over a vector or array in Rust?
✅ Use for item in collection.iter() to borrow each item or .into_iter() to consume it.


Does Rust have a do...while loop?
❌ No. Rust doesn’t support do...while. You can emulate it using loop with if break.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Rust – Loops (General Overview)

Or Copy Link

CONTENTS
Scroll to Top