Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 301
eisterman Avatar asked Mar 14 '18 10:03

eisterman


People also ask

What does ITER () do in Rust?

The iter() method returns an iterator object of the collection. Values in an iterator object are called items. The next() method of the iterator can be used to traverse through the items. The next() method returns a value None when it reaches the end of the collection.

Are Rust iterators lazy?

In Rust, iterators are lazy, meaning they have no effect until you call methods that consume the iterator to use it up.

What does collect () do in Rust?

collect() can take all the values in an Iterator 's stream and stick them into a Vec . And the map method is now generating Result<i32, &str> values, so everything lines up.

Does Rust use iterators?

Obviously, Rust comes with support for loops and iterators as well, and, just like in many other languages, iterators can be implemented from scratch. In this article we're going to take a closer look at the Iterator and IntoIterator traits to create iterators and turning existing types into iterators as well.


2 Answers

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

like image 83
E_net4 stands with Ukraine Avatar answered Sep 28 '22 02:09

E_net4 stands with Ukraine


I am partial to the filter_map version

fn main() {
    let v = vec![1, 2, 3];
    let n = 1;
    let x: Vec<_> = v.into_iter()
        .enumerate()
        .filter_map(|(i, e)| if i != n { Some(e) } else { None })
        .collect();
    println!("{:?}", x);
}

Playground

like image 22
user25064 Avatar answered Sep 28 '22 00:09

user25064