Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When looping, how does .iter() differ from a reference (&)?

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.

like image 846
KChaloux Avatar asked Sep 15 '15 17:09

KChaloux


1 Answers

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.

like image 60
Shepmaster Avatar answered Sep 28 '22 09:09

Shepmaster