5
从the documentation:为什么`Iterator.find()`需要一个可变的`self`引用?
fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
where P: FnMut(&Self::Item) -> bool
我不明白为什么它需要一个可变的裁判self
。有人可以解释吗?
从the documentation:为什么`Iterator.find()`需要一个可变的`self`引用?
fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
where P: FnMut(&Self::Item) -> bool
我不明白为什么它需要一个可变的裁判self
。有人可以解释吗?
它需要能够改变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
}
感谢。非常明显! –