tshepang
tshepang

Reputation: 12459

What is the difference between len() and count()?

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

Answers (1)

Peter Uhnak
Peter Uhnak

Reputation: 10217

vector.len()

Returns the number of elements in the vector.

iter.len()

Return the exact length of the iterator.

iter.count()

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

Related Questions