Iterator `skip_last()`?

I would like to take all elements from an iterator, but the last one. Is there a function that do so? Otherwise I will implement my own adaptator using peek(), but if somesome is already usable of-the-self, it would be even nicer.

For information the following code works.

use std::iter::Peekable;

struct SkipLastIterator<I: Iterator>(Peekable<I>);
impl<I: Iterator> Iterator for SkipLastIterator<I> {
    type Item = I::Item;
    fn next(&mut self) -> Option<Self::Item> {
        let item = self.0.next();
        match self.0.peek() {
            Some(_) => Some(item.unwrap()),
            None => None,
        }
    }
}
trait SkipLast: Iterator + Sized {
    fn skip_last(self) -> SkipLastIterator<Self> {
        SkipLastIterator(self.peekable())
    }
}
impl<I: Iterator> SkipLast for I {}
fn main() {
    let x = [1,2,3];
    let y: Vec<_> = x.iter().skip_last().collect();
    println!("{:?}", y); // prints `[1, 2]`
}
1 Like

In your usecase, you want to skip last element of slice or iterator in general?

Only the last one.

scan can be used: (playground)

fn skip_last<T>(mut iter: impl Iterator<Item=T>) -> impl Iterator<Item=T> {
    let last = iter.next();
    iter.scan(last, |state, item| {
        std::mem::replace(state, Some(item))
    })
}

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.