Trait ForEachRepeat

Source
pub trait ForEachRepeat {
    // Provided method
    fn for_each_repeat<B, C>(
        &mut self,
        f: impl FnMut(Self::Item) -> LoopControl<B, C, Self::Item>,
    ) -> Option<B>
       where Self: Iterator { ... }
}
Expand description

Consumes the iterator by calling the closure on each element, the next iteration is controlled by returned LoopControl variant.

It works similar to try_for_each method on Iterator.

§Example

Basic example:

use for_each_repeat::{LoopControl, ForEachRepeat};

let r = (2..100).for_each_repeat(|x| {
    if 403 % x == 0 {
        return LoopControl::Break(x);
    }

    LoopControl::CONTINUE
});
assert_eq!(r, Some(13));

§Repeat variant:

use for_each_repeat::{LoopControl, ForEachRepeat};

let mut xs = vec![1, 2, 3, 4, 5];

let break_value: Option<()> = xs.iter_mut().for_each_repeat(|x| {
    if *x < 5 {
        *x += 1;
        return LoopControl::Repeat(x);
    }
    LoopControl::CONTINUE
});
assert_eq!(xs, &[5; 5]);
assert_eq!(break_value, None);

§Blanket impl

This trait is implemented for all Iterators automatically – you don’t need to implement it. Just import it in your code:

use for_each_repeat::ForEachRepeat;

Provided Methods§

Source

fn for_each_repeat<B, C>( &mut self, f: impl FnMut(Self::Item) -> LoopControl<B, C, Self::Item>, ) -> Option<B>
where Self: Iterator,

Consumes the iterator, calls closure for each element. Next iteration is controlled by LoopControl variant.

§Example
use for_each_repeat::{LoopControl, ForEachRepeat};

let r = (2..100).for_each_repeat(|x| {
    if 403 % x == 0 {
        return LoopControl::Break(x);
    }

    LoopControl::CONTINUE
});
assert_eq!(r, Some(13));

See trait’s documentation for more. See also: Iterator::try_for_each.

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§