为什么`Iterator.find()`需要一个可变的`self`引用?

Pet*_*all 5 iterator rust

文档:

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

我不明白为什么它需要一个可变的参考self.谁能解释一下?

She*_*ter 6

它需要能够变异,self因为它正在推进迭代器.每次调用时next,迭代器都会发生变异:

fn next(&mut self) -> Option<Self::Item>;
Run Code Online (Sandbox Code Playgroud)

这是执行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
}
Run Code Online (Sandbox Code Playgroud)