[英]Why does `Iterator.find()` require a mutable `self` reference?
從文檔 :
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>;
這是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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.