While playing with Rust, I discovered that you can loop over Vec
s and HashMap
s (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.
Yes, they are identical.
The implementation of
IntoIterator
for&Vec<T>
:The implementation of
IntoIterator
for&HashMap<K, V, S>
:Note that both just call
iter()
.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.