The for statement is a shortcut to iterate over an iterator object or an
object convertible into an iterator.
If the object on which the loop is applied is not an iterator but
implements the IntoIterator trait, then a call to into_iter() is made
for us to convert the object.
This is what happens for instance with collections like Vec.
It is implemented as a loop statement with a call to the next() method
of the iterator at its start.
In the following example, we use the for statement to iterate over an
array:
let a = [1, 2, 3, 4];
for n in a {
print!("{n} ");
}
println!();1 2 3 4
A range being an iterator, we can use the for statement on it:
for i in 1..=10 {
print!("{i} ");
}
println!();1 2 3 4 5 6 7 8 9 10
Many methods (see Table 2 for a list of
the main iterator methods) can be called onto the iterator to transform
it.
For instance, in the following example, we reverse the range to iterate
from higher values to lower values, using the rev() iterator method:
for i in (1..=10).rev() {
print!("{i} ");
}
println!();10 9 8 7 6 5 4 3 2 1
As for the loop statement:
The
continuekeyword is used to skip a step.The
breakkeyword is used to exit the loop prematurely.Labels are used to exit nested loops.