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?
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.
In Rust, iterators are lazy, meaning they have no effect until you call methods that consume the iterator to use it up.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With