While playing with Rust, I discovered that you can loop over Vecs and HashMaps (and probably others) by reference, instead of using .iter().
let xs = vec![1, 2, 3, 4, 5];
for x in &xs {
println!("x == {}", x);
}
The .iter() function seems to have the same behavior.
let xs = vec![1, 2, 3, 4, 5];
for x in xs.iter() {
println!("x == {}", x);
}
Are both methods of looping over a collection functionally identical, or are there subtle differences between how the two behave? I notice that .iter() seems to be the universally preferred approach in examples that I've found.
Are both methods of looping over a collection functionally identical
Yes, they are identical.
The implementation of IntoIterator for &Vec<T>:
impl<'a, T> IntoIterator for &'a Vec<T> {
type Item = &'a T;
type IntoIter = slice::Iter<'a, T>;
fn into_iter(self) -> slice::Iter<'a, T> {
self.iter()
}
}
The implementation of IntoIterator for &HashMap<K, V, S>:
impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
where K: Eq + Hash, S: HashState
{
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
fn into_iter(self) -> Iter<'a, K, V> {
self.iter()
}
}
Note that both just call iter().
I notice that .iter() seems to be the universally preferred approach in examples that I've found.
I use collection.iter() whenever I want to use an iterator adapter, and I use &collection whenever I want to just iterate directly on the collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With