In Rust, is a vector an Iterator?

前端 未结 1 524
情书的邮戳
情书的邮戳 2020-12-11 00:55

Is it accurate to state that a vector (among other collection types) is an Iterator?

For example, I can loop over a vector in the following way, because

相关标签:
1条回答
  • 2020-12-11 01:14

    No, a vector is not an iterator.

    But it implements the trait IntoIterator, which the for loop uses to convert the vector into the required iterator.

    In the documentation for Vec you can see that IntoIterator is implemented in three ways:

    • for Vec<T>, which is moved and the iterator returns items of type T,
    • for a shared reference &Vec<T>, where the iterator returns shared references &T,
    • and for &mut Vec<T>, where mutable references are returned.

    iter() is just a method in Vec to convert Vec<T> directly into an iterator that returns shared references, without first converting it into a reference. There is a sibling method iter_mut() for producing mutable references.

    0 讨论(0)
提交回复
热议问题