Rust for Loop

Rust Tutorial

🦀 Rust for Loop

Rust for Loop is the most commonly used loop.

It is safe, clean, and iterator-based, meaning no risk of out-of-bounds errors like in C/C++.


 1. Basic for Loop (Range)


Range Meaning

  • 1..5 → 1 to 4

  • 1..=5 → 1 to 5 (inclusive)



 2. for Loop with Step (Reverse / Skip)

▶️ Reverse loop


▶️ Skip values



 3. Looping Through Arrays


 

✔ Safer than index-based access


 4. Looping with Index (enumerate)


 


 5. for Loop with break


✔ Stops loop immediately


 6. for Loop with continue


✔ Skips current iteration


 7. Looping Through Strings


 

⚠️ Strings are UTF-8, so indexing is not allowed.


 8. Nested for Loops



 9. Loop Labels with for


✔ Breaks the outer loop


🔑 for vs Other Loops

Loop Best Use
for Collections & ranges
while Condition-based
loop Infinite/manual

🧠 Key Takeaways

  • Rust has no for(i=0; i<n; i++)

  • for works on iterators

  • Prevents out-of-bounds errors

  • Clean & idiomatic Rust code

You may also like...