A for loop repeats a block for each item in a range or other iterable value. Unlike a while loop, it stops after the range is exhausted instead of repeatedly checking a condition. section 3.2.3
fn main() {
for number in 0..3 {
println!("The number is: {}", number);
}
for number in 0..=3 {
println!("The next number is: {}", number);
}
}
Use a variable such as number to receive each value from a range. The range 0..3 excludes 3, while 0..=3 includes it. section 3.2.3
Choose the loop form that matches the job:
- Use a for loop when you want to perform an action for every value in a known range. section 3.2.3
- Use _ when each iteration needs no item value; Rust avoids creating an unused-variable warning. section 3.2.3
- Use a named variable when the body needs the current item; Rust warns if that variable is never used. section 3.2.3
- Use while or loop when repetition depends on a condition or an explicit break rather than a range. section 3.2.3
fn main() {
for _ in 0..3 {
println!("Printing the same thing three times");
}
}
This version repeats the same statement three times without using the range item. section 3.2.3
Processing items from a collection
A for loop can also unpack each item while it iterates. For example, looping over color-and-amount pairs lets the body compare each amount and report colors below 10. section 3.2.3


























