Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add try_collect method to Itertools #394

Merged
merged 1 commit into from Jan 10, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/lib.rs
Expand Up @@ -1541,6 +1541,35 @@ pub trait Itertools : Iterator {
self.collect()
}

/// `.try_collect()` is more convenient way of writing
/// `.collect::<Result<_, _>>()`
///
/// # Example
///
/// ```
/// use std::{fs, io};
/// use itertools::Itertools;
///
/// fn process_dir_entries(entries: &[fs::DirEntry]) {
/// // ...
/// }
///
/// fn do_stuff() -> std::io::Result<()> {
/// let entries: Vec<_> = fs::read_dir(".")?.try_collect()?;
/// process_dir_entries(&entries);
///
/// Ok(())
/// }
/// ```
#[cfg(feature = "use_std")]
fn try_collect<T, U, E>(self) -> Result<U, E>
where
Self: Sized + Iterator<Item = Result<T, E>>,
Result<U, E>: FromIterator<Result<T, E>>,
{
self.collect()
}

/// Assign to each reference in `self` from the `from` iterator,
/// stopping at the shortest of the two iterators.
///
Expand Down