Rust Loops

Rust Loops – Complete Beginner Guide
Loops are one of the most powerful tools in programming.
They allow your program to:
Repeat actions
Process collections
Automate repetitive tasks
Build real-world logic
Handle dynamic data
In Rust, loops are safe, flexible, and expressive.
If you’re learning Rust, mastering loops is essential.
In this complete beginner guide, you’ll learn:
What loops are in Rust
The three types of loops
loopwhileforBreaking and continuing
Loop labels
Loop expressions
Common mistakes
Best practices
Real-world examples
Let’s dive in
What Are Loops in Rust?
A loop allows code to execute repeatedly until a condition is met.
Without loops, you would have to write repetitive code manually.
Example without loop:
1 2 3 | println!("Hello"); println!("Hello"); println!("Hello"); |
With loop:
1 2 3 | for _ in 0..3 { println!("Hello"); } |
Much cleaner and scalable.
Types of Loops in Rust
Rust provides three types of loops:
loop(infinite loop)while(conditional loop)for(iterator loop)
Each has its own use case.
The loop Keyword (Infinite Loop)
loop creates an infinite loop.
Example:
1 2 3 4 5 | fn main() { loop { println!("Running forever..."); } } |
- This will run forever unless stopped manually.
Breaking Out of a loop
Use break to exit.
1 2 3 4 5 6 7 8 | fn main() { let mut count = 0;loop { if count == 5 { break; }println!("{}", count); count += 1; } } |
This prints numbers 0 to 4.
Returning Values from a Loop
Rust allows loop to return a value.
Example:
1 2 3 4 5 6 7 8 9 | fn main() { let mut counter = 0;let result = loop { counter += 1;if counter == 10 { break counter * 2; } }; println!("Result: {}", result); } |
This is unique and powerful.
The while Loop
The while loop runs while a condition is true.
Syntax:
1 2 3 | while condition { // code } |
Example:
1 2 3 4 5 6 | fn main() { let mut number = 5;while number > 0 { println!("{}", number); number -= 1; } } |
Runs until condition becomes false.
Important Rule
The condition must evaluate to a Boolean.
Rust does NOT allow:
1 2 | while 1 { } |
The condition must be explicit.
The for Loop (Most Common in Rust)
The for loop is used to iterate over a range or collection.
Example with range:
1 2 3 4 5 | fn main() { for i in 1..5 { println!("{}", i); } } |
Output:
1
2
3
4
Note: 1..5 excludes 5.
Inclusive Range
1 2 3 | for i in 1..=5 { println!("{}", i); } |
Includes 5.
Iterating Over Arrays
1 2 3 4 5 | fn main() { let numbers = [10, 20, 30, 40];for number in numbers { println!("{}", number); } } |
Clean and safe iteration.
Using continue in Loops
continue skips the current iteration.
Example:
1 2 3 4 5 6 7 | fn main() { for i in 1..6 { if i == 3 { continue; }println!("{}", i); } } |
3 is skipped.
Using break in Loops
Stops the loop immediately.
Example:
1 2 3 4 5 | for i in 1..10 { if i == 5 { break; }println!("{}", i); } |
Stops when i becomes 5.
Loop Labels (Advanced but Useful)
Rust supports labeled loops.
Example:
1 2 3 4 5 6 7 8 | fn main() { 'outer: loop { println!("Outer loop");loop { println!("Inner loop"); break 'outer; } } } |
This breaks the outer loop from inside the inner loop.
Infinite Loops with Conditions
Instead of:
1 2 | while true { } |
Use:
1 2 | loop { } |
Cleaner and more idiomatic.
Looping with enumerate()
You can get index and value.
1 2 3 4 5 | fn main() { let items = ["A", "B", "C"];for (index, value) in items.iter().enumerate() { println!("{}: {}", index, value); } } |
Very useful in real projects.
Real-World Example: Simple Counter App
1 2 3 4 5 6 | fn main() { let mut count = 0;while count < 5 { println!("Count: {}", count); count += 1; } } |
Common in games, timers, simulations.
Real-World Example: Finding Even Numbers
1 2 3 4 5 6 7 | fn main() { for i in 1..=10 { if i % 2 == 0 { println!("Even: {}", i); } } } |
Combines loops and conditions.
Nested Loops
You can nest loops inside loops.
Example:
1 2 3 4 5 6 7 | fn main() { for i in 1..=3 { for j in 1..=3 { println!("({}, {})", i, j); } } } |
Used in:
Matrix operations
Grid systems
Games
Algorithms
Common Beginner Mistakes
- Forgetting
mutfor counters - Infinite loops without break
- Wrong range (exclusive vs inclusive)
- Using
while trueinstead ofloop Modifying collection while iterating
Loop Performance in Rust
Rust loops are:
Memory-safe
Fast
Optimized by compiler
Zero-cost abstractions
The for loop is preferred over manual indexing.
Instead of:
1 2 3 | for i in 0..array.len() { println!("{}", array[i]); } |
Write:
1 2 3 | for item in array { println!("{}", item); } |
Cleaner and safer.
Best Practices for Rust Loops
- Prefer
foroverwhilewhen iterating - Use
looponly when necessary - Avoid deep nesting
- Use clear variable names
- Keep loop bodies small
- Break early when possible
When to Use Each Loop Type
Makeloop when:
You need infinite looping
You want to return values
Use while when:
Loop depends on condition
Use for when:
Iterating over ranges
Working with collections
Writing idiomatic Rust
Frequently Asked Questions (FAQs)
1. How many types of loops are in Rust?
Rust has three main loop types: loop, while, and for.
2. What is the difference between for and while in Rust?
for is used for iterating over ranges and collections, while while runs as long as a condition remains true.
3. Can loops return values in Rust?
Yes. The loop keyword can return a value using break.
4. What does continue do in Rust loops?
It skips the current iteration and moves to the next one.
5. Which loop is most commonly used in Rust?
The for loop is the most commonly used and idiomatic loop in Rust.
Final Thoughts
Rust loop are:
Powerful
Safe
Flexible
Expressive
Efficient
They allow you to:
Repeat tasks
Process data
Build algorithms
Create real-world applications
Mastering loop is a major milestone in your Rust learning journey.
