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

时间:2015-11-04 14:12:12

标签: iterator rust

来自the documentation

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

我不明白为什么它需要self的可变引用。有人可以解释一下吗?

1 个答案:

答案 0 :(得分:6)

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

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

以下是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
}
相关问题