Searching through iterators
Iterator::find is a function which iterates over an iterator and searches for the
first value which satisfies some condition. If none of the values satisfy the
condition, it returns None. Its signature:
pub trait Iterator<T> {
// The type being iterated over.
type Item;
// `find` takes `ref self` meaning the caller may be
// modified, but not consumed.
fn find<
P,
// `Fn` meaning that any captured variable will not be consumed. `@Self::Item` states it
// takes arguments to the closure by snapshot.
+core::ops::Fn<P, (@Self::Item,)>[Output: bool],
+Destruct<P>,
+Destruct<T>,
+Destruct<Self::Item>,
>(
ref self: T, predicate: P,
) -> Option<
Self::Item,
>;
}
fn main() {
let array = array![1_u8, 2, 3];
let span = array![4_u8, 5, 6].span();
// `into_iter()` for arrays yields elements by value
let mut iter = array.into_iter();
// `into_iter()` for spans yields elements by snapshot
let mut into_iter = span.into_iter();
// `into_iter()` for arrays yields `@T`, and we want to reference one of
// its items, so we have to destructure `@T` to `T`
println!("Find 2 in array: {:?}", iter.find(|x| *x == 2));
// `into_iter()` for spans yields `@T`, and we want to reference one of
// its items, so we have to compare with `@@T`
println!("Find 2 in span: {:?}", into_iter.find(|x| x == @@2));
}
Iterator::find gives you a snapshot of the item.