TryMapAll

Trait TryMapAll 

Source
pub trait TryMapAll {
    type Item;

    // Required method
    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.

See TryMapAll::try_map_all.

Once Try (#42327) is stabilized, hopefully the Result and Option variants can be merged and generalized.

Required Associated Types§

Required Methods§

Source

fn try_map_all<T, E>( self, f: impl Fn(Self::Item) -> Result<T, E>, ) -> Result<IntoIter<T>, E>

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 Options 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.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<I: Iterator> TryMapAll for I

Source§

type Item = <I as Iterator>::Item