Loops in Rust
In this lesson, you will learn how to repeat actions in Rust using loops. Loops allow you to execute a block of code multiple times until a condition is met.
Rust provides several looping constructs that are safe, expressive, and efficient.
Why Loops Are Important
Loops help eliminate repetitive code and make programs more concise.
They are commonly used for:
- Iterating over collections
- Repeating calculations
- Processing user input
- Running tasks until a condition changes
The loop Keyword
The loop keyword creates an infinite loop.
The loop will continue running until it is explicitly stopped.
fn main() {
loop {
println!("This will run forever");
}
}
Infinite loops are useful when building servers or background tasks.
Breaking Out of a Loop
The break statement stops the execution of a loop immediately.
fn main() {
let mut count = 0;
loop {
count += 1;
if count == 5 {
break;
}
}
println!("Loop ended");
}
Once break is executed, the loop terminates.
Returning a Value from a Loop
In Rust, a loop can return a value using break.
This makes loops expressive and useful in assignments.
fn main() {
let result = loop {
let x = 10;
break x * 2;
};
println!("Result: {}", result);
}
The while Loop
The while loop runs as long as a condition is true.
It is useful when the number of iterations is not known in advance.
fn main() {
let mut number = 3;
while number != 0 {
println!("{}", number);
number -= 1;
}
println!("Done!");
}
The for Loop
The for loop is commonly used to iterate over a range or collection.
It is the safest and most frequently used loop in Rust.
fn main() {
for i in 1..5 {
println!("Number: {}", i);
}
}
The range 1..5 includes numbers from 1 to 4.
Inclusive Ranges
To include the ending value in a range, use ..=.
fn main() {
for i in 1..=5 {
println!("{}", i);
}
}
Looping Through an Array
The for loop is often used to iterate through arrays safely.
fn main() {
let numbers = [10, 20, 30, 40];
for n in numbers {
println!("{}", n);
}
}
Rust ensures memory safety while iterating.
Using continue
The continue keyword skips the current iteration and moves to the next one.
fn main() {
for i in 1..=5 {
if i == 3 {
continue;
}
println!("{}", i);
}
}
Here, the value 3 is skipped.
Common Loop Mistakes
- Creating infinite loops without
break - Using incorrect range bounds
- Modifying loop variables incorrectly
📝 Practice Exercises
Exercise 1
Write a loop that prints numbers from 1 to 10.
Exercise 2
Use a while loop to count down from 5.
Exercise 3
Use a for loop to iterate over an array.
Exercise 4
Create a loop that stops when a condition is met.
✅ Practice Answers
Answer 1
fn main() {
for i in 1..=10 {
println!("{}", i);
}
}
Answer 2
fn main() {
let mut x = 5;
while x > 0 {
println!("{}", x);
x -= 1;
}
}
Answer 3
fn main() {
let arr = [1, 2, 3];
for v in arr {
println!("{}", v);
}
}
Answer 4
fn main() {
let mut n = 0;
loop {
n += 1;
if n == 3 {
break;
}
}
}
What’s Next?
Now that you understand loops, you are ready to learn how to define and use functions in Rust.
In the next lesson, you will explore functions in Rust.