簡體   English   中英

為什么`Iterator.find()`需要一個可變的`self`引用?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM