How do I work with the borrow checker in this case?


#1

As the title says how do I work with the borrow checker in this case …

Playpen

use std::iter::Peekable;

pub trait AdvanceWhile<I: Iterator> {
    fn advance_while<P>(&mut self, predicate: P)
        where P: Fn(&I::Item) -> bool;
}

impl<I: Iterator> AdvanceWhile<I> for Peekable<I> {
    fn advance_while<P>(&mut self, predicate: P)
        where P: Fn(&I::Item) -> bool 
    {
        while let Some(val) = self.peek() {
            if predicate(val) {
                self.next();
            } else {
                break;
            }
        }
    }
}

fn main() {
}

#2

You can move the predicate check out of the loop, like this:

use std::iter::Peekable;

pub trait AdvanceWhile<I: Iterator> {
    fn advance_while<P>(&mut self, predicate: P)
        where P: Fn(&I::Item) -> bool;
}

impl<I: Iterator> AdvanceWhile<I> for Peekable<I> {
    fn advance_while<P>(&mut self, predicate: P)
        where P: Fn(&I::Item) -> bool 
    {
        while let Some(cont) = self.peek().map(&predicate) {
            if cont {
                self.next();
            } else {
                break;
            }
        }
    }
}

fn main() {
}

I’m sending it to map, instead of a closure, which makes the borrow end within that expression. The content of the Option is instead the result of predicate, which is then used when deciding what to do.


#3

ogeon, thanks for your answer, it is a very elegant!


#4

This was cross-posted to Stack Overflow