pub fn iterator_from<T, F: FnMut() -> Option<T>>(
    f: F
) -> impl Iterator<Item = T>
Expand description

Turn a closure into an iterator.

Each next() on the iterator will simply call the closure once. The iterator ends when the closure returns None.

Example

use ad_hoc_iterator::iterator_from;

fn count_from_to(n: usize, m: usize) -> impl Iterator<Item = usize> {
    let mut i = n;
    iterator_from(move || {
        if i < m {
            i += 1;
            Some(i - 1)
        } else {
            None
        }
    })
}
Examples found in repository?
examples/playground.rs (lines 17-24)
15
16
17
18
19
20
21
22
23
24
25
fn count_from_to(n: usize, m: usize) -> impl Iterator<Item = usize> {
    let mut i = n;
    iterator_from(move || {
        if i < m {
            i += 1;
            Some(i - 1)
        } else {
            None
        }
    })
}