How to remove some items in the iterator and send the remaining

So, what I want is the take method but, instead of making it yield elements by 'n' amount, it should remove elements by that amount and gives Iterator with remaining element.
(I know that I can just write a loop that calls by 'n' amount so as to remove amount of elements. but, for me an actual library method can look lot more nicer and I've a superstition that umm, calling like that might make some optimization(I don't know))
Actually, for my case it would be even better if there is a method that gives both (i.e., an iterator for upto n elements and iterator with elements after n amount) in the form of a tuple. That would be the ideal method for me.

The direct opposite of take is skip. You can also approximate this by calling nth(n-1) to consume the prior elements, which is sometimes nice because it doesn't change the iterator type like the Skip wrapper.

1 Like

You can't quite do that, because to get the n+1th element you have to do something with the first n elements, but if you can process them one by one, by_ref might be what you're looking for. You can combine it with take(n):

1 Like

This doesn't really for me since it gives me borrow error.
This is not my like actual code but, this is way I'll be using it.

fn main() {
    let mut a = [1,2,3,4,].iter();
    let b = a.by_ref().take(3);
    for i in a { println!("{}", i); }
    for i in b { println!("{}", i); }

Now if I interchange line 4 and line 5, it will compile but for me in my actual code the variable a comes before b. However, for me I can use clone() so no worries.

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.