Rust Reference ยท Iterators
Iterators from closures: from_fn, successors and repeat_with
Reference for building Rust iterators from closures: std::iter::from_fn, successors, repeat_with, once_with and empty, with stateful generators and stop rules.
You do not always need a struct and an impl Iterator to make an iterator. The std::iter module has constructors that turn a closure into one. from_fn calls your closure each time next() is needed and ends when it returns None. successors starts from a first value and computes each next value from the previous one. repeat_with calls a closure forever to produce new items.
These are ideal for sequences with a little hidden state: counters, Fibonacci numbers, repeated halving, reading until a sentinel.
use std::iter; let powers: Vec<u32> = iter::successors(Some(1u32), |&n| n.checked_mul(10)).collect();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub fn from_fn<T, F>(f: F) -> FromFn<F> where F: FnMut() -> Option<T>; pub fn successors<T, F>(first: Option<T>, succ: F) -> Successors<T, F> where F: FnMut(&T) -> Option<T>; pub fn repeat_with<A, F>(repeater: F) -> RepeatWith<F> where F: FnMut() -> A; pub fn once_with<A, F>(make: F) -> OnceWith<F> where F: FnOnce() -> A; pub fn once<T>(value: T) -> Once<T>; pub fn empty<T>() -> Empty<T>;
| Name | Description |
|---|---|
f |
Closure called by from_fn for every next(); None ends the iterator. |
first |
The first item of successors; pass None for an empty iterator. |
succ |
Receives a reference to the last item and returns the next one, or None to stop. |
repeater |
Closure that produces a fresh value on every call, forever. |
Returns: an iterator struct (FromFn, Successors, ...) that you consume or chain further.
Errors / panics / edge cases: nothing panics by itself. repeat_with is infinite, so always pair it with take, take_while or zip. from_fn and successors do not implement DoubleEndedIterator, so rev() is not available on them.
Usage notes
successorsyields the first value as is, then callssuccon each yielded item; it stops after the firstNone. The closure receives&T, so pattern|&n|forCopytypes.from_fnis not fused by contract: after returningNoneonce, a later call tonext()calls your closure again. Wrap in.fuse()if the closure may produceSomeafter aNone;successorsis already fused.- Capturing state: use
movewhen the closure should own its counters, which is required if you return the iterator from a function (impl Iterator<Item = u64>). - Return type: the closure types are unnameable, so write functions as
fn fib() -> impl Iterator<Item = u64>. once_withandrepeat_withare lazy: the closure runs when the item is needed, unlikeonce(value)andrepeat(value), where the value already exists.repeatrequiresClone.- When to prefer a struct: if the iterator needs extra methods,
size_hintor double-ended behavior, implementIteratoryourself. - Overflow: inside debug builds
a + bpanics on overflow;successorswithchecked_*oru128avoids that.