Reputation: 12459
In code below, I get the same result whether I use len
or count
:
fn main() {
let vector = [0, 1, 2];
assert_eq!(vector.iter().count(), vector.iter().len());
}
len
seems more generic since I can also do this:
assert_eq!(vector.len(), 3);
So, what's the difference between the two... why use one and not the other?
Upvotes: 47
Views: 38225
Reputation: 10217
Returns the number of elements in the vector.
Return the exact length of the iterator.
Counts the number of elements in this iterator.
So while they return the same value, count
will actually count the elements. Note that len
is available only for ExactSizeIterator; so if the value is lazy-retrieved the total length may not be available and you need to explicitly count it.
Upvotes: 49