2021年3月5日星期五

Optionally call `skip` in a custom iterator `next()` function

I have a custom iterator and I would like to optionally call .skip(...) in the custom .next() method. However, I get a type error because Skip != Iterator.

Sample code is as follows:

struct CrossingIter<'a, T> {      index: usize,      iter: std::slice::Iter<'a, T>,  }    impl<'a, T: Float> Iterator for CrossingIter<'a, T> {      type Item = (usize, T);          fn next(&mut self) -> Option<(usize, T)> {          let iter = (&mut self.iter).enumerate();                     let iter = if self.index == 0 {              self.index += 3;              iter.skip(3)          } else {              iter          }            // lots of code here working with the new iterator                    iter.next()      }  }  

The issue is that after calling .skip(3), the type of iter has changed. One solution would be to duplicate the // lots of code ... in each branch of the if statement, but I'd rather not.

My question is: Is there a way to conditionally apply skip(...) to an iterator and continue working with it without duplicating a bunch of code?

https://stackoverflow.com/questions/66502055/optionally-call-skip-in-a-custom-iterator-next-function March 06, 2021 at 11:25AM

没有评论:

发表评论