IterFolding

Trait IterFolding 

Source
pub trait IterFolding<T> {
    // Required method
    fn with_folding<O, F, R>(self, f: F) -> T
       where Self: Iterator<Item = T> + Sized,
             F: Fn(BreakingIterator<'_, Self, T::Residual>) -> O,
             T: Try<Output = O, Residual = R>;
}
Expand description

Including this trait adds the with_folding helper function to any normal iterator.

This function allows you to do any fold-style operation (like Iterator::max, Iterator::max_by_key, Iterator::find, or even Iterator::fold itself) while breaking on any divergent value (like Err or None).

This helps avoid the proliferation of various variants of folding functions just to deal specifically with results, and helps errors propagate more easily. The alternative is to collect into a Result<Vec<_>,_> first, which may not be very efficient.

Example:

let items = [
    Ok(1),
    Ok(2),
    Ok(1),
    Err("boom"),
    Err("hi"),
    Ok(3),
    Ok(1),
    Err("zoop"),
    Ok(5)
];

let with = items
    .into_iter()
    .with_folding(|i| i.sum::<u32>());

let without = items
    .into_iter()
    .collect::<Result<Vec<_>,_>>()
    .map(|v|
        v.into_iter().sum::<u32>()
    );

Required Methods§

Source

fn with_folding<O, F, R>(self, f: F) -> T
where Self: Iterator<Item = T> + Sized, F: Fn(BreakingIterator<'_, Self, T::Residual>) -> O, T: Try<Output = O, Residual = R>,

Takes the self iterator and calls f with an iterator that will provide the ‘normal’ values, returning either the first encountered failure value or the result of the function.

Implementors§

Source§

impl<I, T> IterFolding<T> for I
where I: Iterator<Item = T>,