111 cards
Beginner - Basics
How do you use a for loop in Rust?
fn main() {
// Iterate over a range
for i in 0..5 {
println!("i = {}", i); // 0, 1, 2, 3, 4
}
// Inclusive range
for i in 1..=3 {
println!("i = {}", i); // 1, 2, 3
}
// Iterate over array
let arr = [10, 20, 30];
for element in arr {
println!("Value: {}", element);
}
}
Copy, paste and run the code above in Rust Playground.
for loops over iterators. Use .. for exclusive range, ..= for inclusive.
Read more in TRPL - Looping Through a Collection with for.