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

From the documentation :

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

I do not understand why he needs to change the to self parameter. Can someone explain?

+5
source share
1 answer

It should be able to mutate self , because it is promoting an iterator. Each time you call next , the iterator mutates:

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

Here is the find implementation :

 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 } 
+6
source

Source: https://habr.com/ru/post/1235203/


All Articles