Trait core::iter::ExactSizeIterator [] [src]

pub trait ExactSizeIterator: Iterator {
    fn len(&self) -> usize { ... }
}

An iterator that knows its exact length.

Many Iterators don't know how many times they will iterate, but some do. If an iterator knows how many times it can iterate, providing access to that information can be useful. For example, if you want to iterate backwards, a good start is to know where the end is.

When implementing an ExactSizeIterator, You must also implement Iterator. When doing so, the implementation of size_hint() must return the exact size of the iterator.

The len() method has a default implementation, so you usually shouldn't implement it. However, you may be able to provide a more performant implementation than the default, so overriding it in this case makes sense.

Examples

Basic usage:

fn main() { // a finite range knows exactly how many times it will iterate let five = 0..5; assert_eq!(5, five.len()); }
// a finite range knows exactly how many times it will iterate
let five = 0..5;

assert_eq!(5, five.len());

In the module level docs, we implemented an Iterator, Counter. Let's implement ExactSizeIterator for it as well:

fn main() { struct Counter { count: usize, } impl Counter { fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = usize; fn next(&mut self) -> Option<usize> { self.count += 1; if self.count < 6 { Some(self.count) } else { None } } } impl ExactSizeIterator for Counter { // We already have the number of iterations, so we can use it directly. fn len(&self) -> usize { self.count } } // And now we can use it! let counter = Counter::new(); assert_eq!(0, counter.len()); }
impl ExactSizeIterator for Counter {
    // We already have the number of iterations, so we can use it directly.
    fn len(&self) -> usize {
        self.count
    }
}

// And now we can use it!

let counter = Counter::new();

assert_eq!(0, counter.len());

Provided Methods

fn len(&self) -> usize

Returns the exact number of times the iterator will iterate.

This method has a default implementation, so you usually should not implement it directly. However, if you can provide a more efficient implementation, you can do so. See the trait-level docs for an example.

This function has the same safety guarantees as the size_hint() function.

Examples

Basic usage:

fn main() { // a finite range knows exactly how many times it will iterate let five = 0..5; assert_eq!(5, five.len()); }
// a finite range knows exactly how many times it will iterate
let five = 0..5;

assert_eq!(5, five.len());

Implementors