What is a For Loop in Rust?
A for loop in Rust is used to iterate over a sequence of items. It eliminates the need for manual index handling, making the loop cleaner, safer and less error-prone.
Syntax of the For Loop
for variable in iterable {
// Code to execute
}
- variable: Represents each item in the sequence.
- iterable: A collection, range, or any iterator over which the loop iterates.
Advantages of Using the For Loop in Rust
- Safety: No need for manual index management, reducing the risk of runtime errors.
- Efficiency: Rust optimizes iteration to be fast and memory-safe.
- Clarity: Code becomes easier to read and maintain.
Examples of For Loop in Rust
1. Iterating Over a Range
You can use a for loop to iterate over a range of numbers.
fn main() {
for number in 1..5 {
println!("Number: {}", number);
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
- The range 1. .5 includes numbers from 1 to 4, but excludes 5.
- To include the upper bound, use 1. .=5.
2. Iterating Over an Array
The for loop can iterate through an array or a vector.
fn main() {
let fruits = ["apple", "banana", "cherry"];
for fruit in fruits {
println!("Fruit: {}", fruit);
}
}
Output:
Fruit: apple
Fruit: banana
Fruit: cherry
3. Iterating Over a Vector
Vectors are commonly used in Rust. The for
loop easily iterates over them.
fn main() {
let numbers = vec![10, 20, 30, 40];
for num in &numbers {
println!("Number: {}", num);
}
}
Output:
Number: 10
Number: 20
Number: 30
Number: 40
- Using &numbers allows the loop to borrow the vector without taking ownership.
4. Iterating with Indices
The .enumerate() method provides both the index and the value during iteration.
fn main() {
let colors = ["red", "green", "blue"];
for (index, color) in colors.iter().enumerate() {
println!("Index: {}, Color: {}", index, color);
}
}
Output:
Index: 0, Color: red
Index: 1, Color: green
Index: 2, Color: blue
Working with Ranges in For Loops
a. Exclusive Range (. .)
Iterates up to, but not including, the upper bound.
rustCopy codefor i in 1..5 {
println!("{}", i);
}
b. Inclusive Range (. .=)
Iterates up to and includes the upper bound.
for i in 1..=5 {
println!("{}", i);
}
Using Break and Continue in For Loops
Break Statement
Exits the loop prematurely.
fn main() {
for i in 1..10 {
if i == 5 {
break;
}
println!("{}", i);
}
}
Output:
1
2
3
4
Continue Statement
Skips the current iteration and proceeds to the next one.
fn main() {
for i in 1..10 {
if i == 5 {
continue;
}
println!("{}", i);
}
}
Output:
1
2
3
4
6
7
8
9
Nested For Loops
You can use for loops inside other loops to handle multi-dimensional data or complex tasks.
Example: Multiplication Table
fn main() {
for i in 1..=3 {
for j in 1..=3 {
print!("{} ", i * j);
}
println!();
}
}
Output:
1 2 3
2 4 6
3 6 9
Iterating Over Strings
You can iterate over characters in a string.
fn main() {
let word = "Rust";
for c in word.chars() {
println!("{}", c);
}
}
Output:
R
u
s
t