Trait try_all::TryMapAll [−][src]
pub trait TryMapAll { type Item; fn try_map_all<T, E>(
self,
f: impl Fn(Self::Item) -> Result<T, E>
) -> Result<IntoIter<T>, E>; }
Expand description
Trait providing try map (result) extensions to Iterators.
Once Try
(#42327) is stabilized, hopefully the Result
and Option
variants can be merged and generalized.
Associated Types
Required methods
fn try_map_all<T, E>(
self,
f: impl Fn(Self::Item) -> Result<T, E>
) -> Result<IntoIter<T>, E>
[src]
fn try_map_all<T, E>(
self,
f: impl Fn(Self::Item) -> Result<T, E>
) -> Result<IntoIter<T>, E>
[src]Applies a closure on all items of the iterator until one fails (or all succeed).
Arguments
f
: fallible mapping function
Returns
The iterator of all successes, or the first failure.
Examples
Useful for propagating failures from within closures with ?
operator:
fn all_numbers_x2(strs: &Vec<&str>) -> Result<Vec<u64>, std::num::ParseIntError> { Ok(strs.iter().try_map_all(|s| Ok(s.parse::<u64>()?*2))?.collect()) }
Equivalence
iter.try_map_all(f)
is equivalent to iter.map(f).try_all()
, except the latter works with Option
s just as well (or check out TryMapAllOption::try_map_all_opt()
).
Additionally, it is equivalent to
let mut acc = Vec::new(); for item in iter { acc.push(f(item)?); } Ok(acc)
Due to the nature of operation, the function has to collect intermediate results.
In other words, if f
has side effects, expect them for all applications until [including] first failure.
Additionally, this won’t work on infinite sequences :o.