capypad
0 day streak
rust / beginner
Snippet

For Loops with Range Expressions

Rust for loops work with ranges using .. syntax. The range 0..5 produces values 0, 1, 2, 3, 4. You can also iterate over arrays using iter() and enumerate() to get both index and value.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
fn main() {
for i in 0..5 {
println!("Count: {}", i);
}
let colors = ["Red", "Green", "Blue"];
for (index, color) in colors.iter().enumerate() {
println!("{}: {}", index, color);
}
}
Breakdown
1
for i in 0..5
Iterates from 0 to 4 (exclusive end)
2
colors.iter().enumerate()
Creates an iterator that yields index and value pairs