當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Rust Iterator.find用法及代碼示例

本文簡要介紹rust語言中 std::iter::Iterator.find 的用法。

用法

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

搜索滿足謂詞的迭代器元素。

find() 采用返回 truefalse 的閉包。它將這個閉包應用於迭代器的每個元素,如果它們中的任何一個返回 true ,那麽 find() 返回 Some(element) 。如果它們都返回 false ,則返回 None

find() 短路;換句話說,一旦閉包返回 true ,它將停止處理。

因為find() 采用引用,並且許多迭代器迭代引用,這導致參數是雙重引用的可能令人困惑的情況。您可以在下麵的示例中使用 &&x 看到這種效果。

例子

基本用法:

let a = [1, 2, 3];

assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));

assert_eq!(a.iter().find(|&&x| x == 5), None);

停在第一個 true

let a = [1, 2, 3];

let mut iter = a.iter();

assert_eq!(iter.find(|&&x| x == 2), Some(&2));

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(&3));

請注意 iter.find(f) 等同於 iter.filter(f).next()

相關用法


注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 std::iter::Iterator.find。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。