Is it possible to get the last element returned by an iterator?

I have an iterator, and I would like to consume it and return the last value. Is there a more convenient way to do it than this?

fn last<T, It: Iterator<Item=T>(iter: It) -> Option<T> {
    let mut last = None;
    for value in iter {
        last = Some(value);
    }
    last
}

This implementation is especially stupid since it should take advantage of specific traits, like ExactSizeIterator if possible.

Note: if the iterator is infinite, it should hang forever, that's expected.

1 Like

Iterator has a last() method. Some iterators do optimize this to jump to the end, but some like Map cannot due to possible side effects.

3 Likes

I think I search for first() and since it didn't exist, I assumed last() would not exists either.

first() is just next(), without consuming the iterator. There's also DoubleEndedIterator::next_back(), which may be more direct than last() since it dodges the question about side effects.

7 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.