Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `Iterator.find()` require a mutable `self` reference?

Tags:

iterator

rust

From the documentation:

fn find<P>(&mut self, predicate: P) -> Option<Self::Item> 
where P: FnMut(&Self::Item) -> bool

I don't see why it needs a mutable ref to self. Can someone explain?

like image 810
Peter Hall Avatar asked Nov 04 '15 14:11

Peter Hall


1 Answers

It needs to be able to mutate self because it is advancing the iterator. Each time you call next, the iterator is mutated:

fn next(&mut self) -> Option<Self::Item>;

Here is the implementation of find:

fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
    Self: Sized,
    P: FnMut(&Self::Item) -> bool,
{
    for x in self.by_ref() {
        if predicate(&x) { return Some(x) }
    }
    None
}
like image 194
Shepmaster Avatar answered Nov 07 '22 05:11

Shepmaster