Filter adapter for LendingIterator requires Polonius · Issue #92985 · rust-lang/rust (original) (raw)

Skip to content

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

@jackh726

Description

@jackh726

Currently, you can't write a safe filter adapter for a LendingIterator with GATs without polonius.

#![feature(generic_associated_types)]

trait LendingIterator { type Item<'a> where Self: 'a; fn next(&mut self) -> Option<Self::Item<'_>>;

fn filter<P>(self, predicate: P) -> Filter<Self, P>
where
    Self: Sized,
    P: FnMut(&Self::Item<'_>) -> bool,
{
    Filter {
        iter: self,
        predicate,
    }
}

}

pub struct Filter<I, P> { iter: I, predicate: P, } impl<I: LendingIterator, P> LendingIterator for Filter<I, P> where P: FnMut(&I::Item<'_>) -> bool, { type Item<'a> where Self: 'a = I::Item<'a>;

fn next(&mut self) -> Option<I::Item<'_>> {
    while let Some(item) = self.iter.next() {
        if (self.predicate)(&item) {
            return Some(item);
        }
    }
    return None;
}

}

fn main() {}

Playground
Minimal Iterator equivalent