Search code examples
iteratorrustskip

How can I skip the Nth element in a Rust iterator?


Iterators have a skip method that skips the first n elements:

let list = vec![1, 2, 3];
let iterator = list.iter();
let skip_iter = iterator.skip(2); //skip the first 2 elements

I could not find a method to skip only the n-th element in the iterator. Do I need to implement something on my own or is there a method somewhere I haven't found?


Solution

  • That seems to be a very specific operation. There is no adaptor for that in the standard library or the itertools crate.

    It's easy to implement nonetheless. One could enumerate each element and filter on the index:

    iter.enumerate().filter(|&(i, _)| i != n).map(|(_, v)| v)
    

    Playground