Do iterators return a reference to items or the value of the items in Rust?
There's no general answer to this question. An iterator can return either. You can find the type of the items by looking up the associated type Iterator::Item
in the documentation. The documentation of Vec::iter()
, for example, tells you that the return type is std::slice::Iter
. The documentation of Iter
in turn has a list of the traits the type implements, and the Iterator
trait is one of them. If you expand the documentation, you can see
type Item = &'a T
which tells you that the item type for the iterator return by Vec<T>::iter()
it &T
, i.e. you get references to the item type of the vector itself.
In the notation
for &item in v.iter() {}
the part after for
is a pattern that is matched against the items in the iterator. In the first iteration &item
is matched against &0
, so item
becomes 0
. You can read more about pattern matching in any Rust introduction.
Another way to iterate over the vector v
is to write
for item in v {}
This will consume the vector, so it can't be used anymore after the loop. All items are moved out of the vector and returned by value. This uses the IntoIterator
trait implemented for Vec<T>
, so look it up in the documentation to find its item type!
The first loop above is usually written as
for &item in &v {}
which borrows v
as a reference &Vec<i32>
, and then calls IntoIterator
on that reference, which will return the same Iter
type mentioned above, so it will also yield references.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…