Function iterator_from

Source
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. The closure will not be called again after that point, even if next() is called again.

ยง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)
15fn count_from_to(n: usize, m: usize) -> impl Iterator<Item = usize> {
16    let mut i = n;
17    iterator_from(move || {
18        if i < m {
19            i += 1;
20            Some(i - 1)
21        } else {
22            None
23        }
24    })
25}