Rust Loops More About For Loops

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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>.



Got any Rust Question?