Skip to content

Commit afcdd69

Browse files
bors[bot]jplatte
andauthored
Merge #394
394: Add try_collect method to Itertools r=jswrenn a=jplatte fixes #359 Co-authored-by: Jonas Platte <[email protected]>
2 parents 641671e + 94218a3 commit afcdd69

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/lib.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1541,6 +1541,35 @@ pub trait Itertools : Iterator {
15411541
self.collect()
15421542
}
15431543

1544+
/// `.try_collect()` is more convenient way of writing
1545+
/// `.collect::<Result<_, _>>()`
1546+
///
1547+
/// # Example
1548+
///
1549+
/// ```
1550+
/// use std::{fs, io};
1551+
/// use itertools::Itertools;
1552+
///
1553+
/// fn process_dir_entries(entries: &[fs::DirEntry]) {
1554+
/// // ...
1555+
/// }
1556+
///
1557+
/// fn do_stuff() -> std::io::Result<()> {
1558+
/// let entries: Vec<_> = fs::read_dir(".")?.try_collect()?;
1559+
/// process_dir_entries(&entries);
1560+
///
1561+
/// Ok(())
1562+
/// }
1563+
/// ```
1564+
#[cfg(feature = "use_std")]
1565+
fn try_collect<T, U, E>(self) -> Result<U, E>
1566+
where
1567+
Self: Sized + Iterator<Item = Result<T, E>>,
1568+
Result<U, E>: FromIterator<Result<T, E>>,
1569+
{
1570+
self.collect()
1571+
}
1572+
15441573
/// Assign to each reference in `self` from the `from` iterator,
15451574
/// stopping at the shortest of the two iterators.
15461575
///

0 commit comments

Comments
 (0)