Rust Loops

Rust Tutorial

🦀 Rust Loops

In Rust Loops provide three main loop types for repeating code:

Rust loops are safe, expressive, and strict.


 1. loop (Infinite Loop)

Runs forever until you stop it using break.


 

✔ Useful for servers, games, event listeners


 2. loop with Return Value

loop can return a value using break.


 


3. while Loop

Runs while a condition is true.


 

✔ Best when loop count is unknown


 4. for Loop (Most Used)

Used to iterate over ranges, arrays, and collections.

▶️ Using range


  • 1..5 → 1 to 4

  • 1..=5 → 1 to 5


▶️ Looping through array


 

✔ Safer than index-based loops


 5. break and continue

▶️ break – exit loop



▶️ continue – skip iteration



 6. Nested Loops



 7. Loop Labels (Advanced but Powerful)

Used to break outer loops.



 8. while let Loop

Used mainly with Option or Result.


 


🔑 Loop Comparison

Loop Best Use
loop Infinite / manual control
while Condition-based
for Iteration over data

🧠 Important Rules

  • Conditions must be bool

  • for loops are safest & preferred

  • No classic for(i=0;i<n;i++) like C

  • Compiler prevents out-of-bounds errors

You may also like...