diff options
| author | Aleksey Kladov <aleksey.kladov@gmail.com> | 2018-03-16 19:38:25 +0300 |
|---|---|---|
| committer | Aleksey Kladov <aleksey.kladov@gmail.com> | 2018-04-03 00:47:00 +0300 |
| commit | 591dd5d992ef5c9eb6a37cf9870c5f094d6363e4 (patch) | |
| tree | 6f9d9b15e368fde649c6ba05113eeae221526217 /src/libcore/iter | |
| parent | 14ac1b5faab32d268a85dfde6c6592b7183c5864 (diff) | |
Add Iterator::find_map
Diffstat (limited to 'src/libcore/iter')
| -rw-r--r-- | src/libcore/iter/iterator.rs | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/src/libcore/iter/iterator.rs b/src/libcore/iter/iterator.rs index 31f77f92435..f039d1730eb 100644 --- a/src/libcore/iter/iterator.rs +++ b/src/libcore/iter/iterator.rs @@ -1745,6 +1745,38 @@ pub trait Iterator { }).break_value() } + /// Applies function to the elements of iterator and returns + /// the first non-none result. + /// + /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`. + /// + /// + /// # Examples + /// + /// ``` + /// #![feature(iterator_find_map)] + /// let a = ["lol", "NaN", "2", "5"]; + /// + /// let mut first_number = a.iter().find_map(|s| s.parse().ok()); + /// + /// assert_eq!(first_number, Some(2)); + /// ``` + #[inline] + #[unstable(feature = "iterator_find_map", + reason = "unstable new API", + issue = "49602")] + fn find_map<B, F>(&mut self, mut f: F) -> Option<B> where + Self: Sized, + F: FnMut(Self::Item) -> Option<B>, + { + self.try_for_each(move |x| { + match f(x) { + Some(x) => LoopState::Break(x), + None => LoopState::Continue(()), + } + }).break_value() + } + /// Searches for an element in an iterator, returning its index. /// /// `position()` takes a closure that returns `true` or `false`. It applies |
