Rust More About For Loops


Example

As mentioned in Basics, we can use anything which implements IntoIterator with the for loop:

let vector = vec!["foo", "bar", "baz"]; // vectors implement IntoIterator
for val in vector {
    println!("{}", val);
}

Expected output:

foo  
bar  
baz

Note that iterating over vector in this way consumes it (after the for loop, vector can not be used again). This is because IntoIterator::into_iter moves self.

IntoIterator is also implemented by &Vec<T> and &mut Vec<T> (yielding values with types &T and &mut T respectively) so you can prevent the move of vector by simply passing it by reference:

let vector = vec!["foo", "bar", "baz"];
for val in &vector {
    println!("{}", val);
}
println!("{:?}", vector);

Note that val is of type &&str, since vector is of type Vec<&str>.