Skip to content
Tutorials Center
My learning

Topics

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.

Rust
use std::iter;
let powers: Vec<u32> = iter::successors(Some(1u32), |&n| n.checked_mul(10)).collect();

Try it

Rust from_fn with captured state

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.

Rust successors, repeat_with and friends

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

Rust
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

  • successors yields the first value as is, then calls succ on each yielded item; it stops after the first None. The closure receives &T, so pattern |&n| for Copy types.
  • from_fn is not fused by contract: after returning None once, a later call to next() calls your closure again. Wrap in .fuse() if the closure may produce Some after a None; successors is already fused.
  • Capturing state: use move when 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_with and repeat_with are lazy: the closure runs when the item is needed, unlike once(value) and repeat(value), where the value already exists. repeat requires Clone.
  • When to prefer a struct: if the iterator needs extra methods, size_hint or double-ended behavior, implement Iterator yourself.
  • Overflow: inside debug builds a + b panics on overflow; successors with checked_* or u128 avoids that.