for loops
for and range
The for in construct can be used to iterate through an Iterator.
One of the easiest ways to create an iterator is to use the range
notation a..b. This yields values from a (inclusive) to b
(exclusive) in steps of one.
Let's write FizzBuzz using for instead of while.
fn main() {
// `n` will take the values: 1, 2, ..., 100 in each iteration
for n in 1..101_u8 {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
}
}
Alternatively, a..=b can be used for a range that is inclusive on both ends.
The above can be written as:
fn main() {
// `n` will take the values: 1, 2, ..., 100 in each iteration
for n in 1..= 100_u8 {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
}
}
for and iterators
The for in construct is able to interact with an Iterator in several ways.
As discussed in the section on the Iterator trait, by default the for
loop will apply the into_iter function to the collection. However, this is
not the only means of converting collections into iterators.
into_iter consumes the collection so that on each iteration the exact
data is provided. Once the collection has been consumed it is no longer
available for reuse as it has been 'moved' within the loop.
into_iter- This consumes the collection so that on each iteration the exact data is provided. Once the collection has been consumed it is no longer available for reuse as it has been 'moved' within the loop.
fn main() {
let names: Array<ByteArray> = array!["Bob", "Frank", "Ferris"];
for name in names.into_iter() {
if name == "Ferris" {
println!("There is a caironaute among us!");
} else {
println!("Hello {}", name);
}
}
println!("names: {:?}", names);
// FIXME ^ Comment out this line
}
Note: The syntax
for elem in collectionis equivalent tofor elem in collection.into_iter()and requires theIntoItertrait to be implemented for the collection.
In the above snippets note the type of match branch, that is the key
difference in the types of iteration. The difference in type then of course
implies differing actions that are able to be performed.