Rust Control Flow
Estimated reading: 3 minutes 113 views

🦀 Rust – For Loops: Efficient Iteration Over Ranges and Collections

🧲 Introduction – Why Learn for Loops in Rust?

In Rust, for loops are the most commonly used and safest way to iterate over ranges, arrays, vectors, and other iterators. Unlike while or loop, the for loop automatically handles boundaries and avoids common errors like off-by-one bugs.

🎯 In this guide, you’ll learn:

  • How to use for loops with ranges and collections
  • The difference between .. and ..=
  • How .iter(), .into_iter(), and .enumerate() work
  • Code examples with real outputs and explanations

🔢 Basic for Loop with a Range

🔹 Code Example:

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

🧠 Explanation:

  • 1..4 creates a range from 1 up to but not including 4
  • Loop runs with i = 1, i = 2, i = 3

📤 Output:

i = 1
i = 2
i = 3

✅ Inclusive Range with ..=

🔹 Code Example:

fn main() {
    for num in 1..=3 {
        println!("Number: {}", num);
    }
}

🧠 Explanation:

  • 1..=3 includes the upper limit, so it runs for 1, 2, and 3

📤 Output:

Number: 1
Number: 2
Number: 3

🧳 Iterating Over an Array

🔹 Code Example:

fn main() {
    let fruits = ["apple", "banana", "cherry"];

    for fruit in fruits.iter() {
        println!("Fruit: {}", fruit);
    }
}

🧠 Explanation:

  • .iter() returns immutable references to each item
  • Loop does not consume the array—fruits remains usable

📤 Output:

Fruit: apple
Fruit: banana
Fruit: cherry

📦 Iterating Over a Vector with .into_iter()

🔹 Code Example:

fn main() {
    let numbers = vec![10, 20, 30];

    for num in numbers.into_iter() {
        println!("Value: {}", num);
    }
}

🧠 Explanation:

  • .into_iter() moves each item out of the vector
  • numbers is no longer usable after the loop

📤 Output:

Value: 10
Value: 20
Value: 30

🔢 Loop with Index Using .enumerate()

🔹 Code Example:

fn main() {
    let languages = ["Rust", "Python", "C++"];

    for (index, lang) in languages.iter().enumerate() {
        println!("{}: {}", index, lang);
    }
}

🧠 Explanation:

  • .enumerate() adds indexing while iterating
  • Returns (index, value) tuple per item

📤 Output:

0: Rust
1: Python
2: C++

⏭️ Skipping and Breaking Inside a for Loop

🔹 Code Example:

fn main() {
    for x in 1..=5 {
        if x == 3 {
            continue; // skip number 3
        }
        if x == 4 {
            break; // exit loop at 4
        }
        println!("x = {}", x);
    }
}

🧠 Explanation:

  • Skips printing 3, exits loop when x == 4

📤 Output:

x = 1
x = 2

📋 Summary – Recap & Next Steps

Rust’s for loop is a concise and safe way to iterate over ranges, arrays, and iterators. It handles bounds and borrowing rules automatically—reducing boilerplate and runtime errors.

🔍 Key Takeaways:

  • for i in 1..5 iterates from 1 to 4; 1..=5 includes 5
  • Use .iter() to borrow, .into_iter() to consume, .enumerate() to count
  • for loops are preferred over manual while when range/collection is known

⚙️ Next up: Dive into Rust – Loop Control to master break, continue, and labeled loops.


❓FAQs


What’s the difference between 1..5 and 1..=5 in Rust?
1..5 is an exclusive range (stops before 5), while 1..=5 is inclusive (includes 5).


Can I use for with arrays and vectors?
✅ Yes. Use .iter() to borrow items, .into_iter() to move them, or .enumerate() for index tracking.


Does for automatically handle out-of-bound errors?
✅ Yes. for is safe and never causes panic due to index overflow like C-style loops.


How do I reverse a for loop?
✅ Use .rev():

for i in (1..=3).rev() {
    println!("{}", i);
}

Share Now :
Share

Rust – For Loops

Or Copy Link

CONTENTS
Scroll to Top