[−][src]Function nom::lib::std::iter::unfold
ⓘImportant traits for Unfold<St, F>
pub fn unfold<St, T, F>(initial_state: St, f: F) -> Unfold<St, F> where
F: FnMut(&mut St) -> Option<T>,
🔬 This is a nightly-only experimental API. (
iter_unfold
)Creates a new iterator where each iteration calls the provided closure
F: FnMut(&mut St) -> Option<T>
.
This allows creating a custom iterator with any behavior
without using the more verbose syntax of creating a dedicated type
and implementing the Iterator
trait for it.
In addition to its captures and environment,
the closure is given a mutable reference to some state
that is preserved across iterations.
That state starts as the given initial_state
value.
Note that the Unfold
iterator doesn’t make assumptions about the behavior of the closure,
and therefore conservatively does not implement FusedIterator
,
or override Iterator::size_hint
from its default (0, None)
.
Examples
Let’s re-implement the counter iterator from module-level documentation:
#![feature(iter_unfold)] let counter = std::iter::unfold(0, |count| { // Increment our count. This is why we started at zero. *count += 1; // Check to see if we've finished counting or not. if *count < 6 { Some(*count) } else { None } }); assert_eq!(counter.collect::<Vec<_>>(), &[1, 2, 3, 4, 5]);