In Rust, when would you build a paginated API client's record stream with std::iter::from_fn or std::iter::successors instead of a struct implementing Iterator?
answer
- a closure as next
- each item from the previous one
- unnameable type, so impl Iterator
- move the captured state
- successors computes one step ahead
basics
~20 sUse iter::from_fn when a closure holding the cursor can act as next, and iter::successors when each page follows from the previous one. Both return unnameable types behind impl Iterator; a struct wins when callers need extra traits or methods.
solid answer
~50 s`std::iter::from_fn(f)` takes an `FnMut() -> Option<T>` and calls it as `next`, so the cursor and a buffer of the current page live as captured variables; returned from a function the closure needs `move`, or rustc reports E0373. `std::iter::successors(first, f)` takes an `Option<T>` and an `FnMut(&T) -> Option<T>` and yields each value computed from the previous one — a natural fit for pages linked by a next cursor, flattened with `flat_map(|page| page.records)`. Both return types contain a closure type you cannot name, so the function returns `impl Iterator<Item = Record>`. Watch the eagerness: `successors` computes the successor as it hands out the current item, so taking page 0 already fetches page 1. Write a struct when the iterator must be stored by name, implement `DoubleEndedIterator` or `ExactSizeIterator`, report a real `size_hint` or expose methods such as the current cursor.
code
rust · 35 linesuse std::iter;
#[derive(Debug)]
struct Page { records: Vec<u32>, next_cursor: Option<u32> }
// Stand-in for an API call: three pages of two records each.
fn fetch_page(cursor: u32) -> Page {
let start = cursor * 10;
let next_cursor = if cursor < 2 { Some(cursor + 1) } else { None };
Page { records: vec![start, start + 1], next_cursor }
}
fn records() -> impl Iterator<Item = u32> {
iter::successors(Some(fetch_page(0)), |page| page.next_cursor.map(fetch_page))
.flat_map(|page| page.records)
}
fn records_from_fn() -> impl Iterator<Item = u32> {
let mut buf = Vec::new().into_iter();
let mut cursor = Some(0);
iter::from_fn(move || loop {
if let Some(r) = buf.next() {
return Some(r);
}
let page = fetch_page(cursor?);
cursor = page.next_cursor;
buf = page.records.into_iter();
})
}
fn main() {
println!("{:?}", records().collect::<Vec<_>>());
println!("{:?}", records_from_fn().take(3).collect::<Vec<_>>());
println!("{:?}", records_from_fn().size_hint());
}go deeper
Know that from_fn turns a closure returning Option<T> into an iterator, and successors builds each item from the previous one.
Explain where the state lives, why move is needed when the iterator is returned, and why the function signature says impl Iterator.
Call out the eagerness of successors for expensive steps such as network fetches, and say which traits and size hints a closure-built iterator cannot offer.
Decide when a public API should expose a named iterator type that can grow methods and trait impls, rather than a closure-built impl Iterator.
## Two shortcuts in std::iter Writing a struct and an `impl Iterator` block is the general way to create an iterator, but std offers two functions that build one from a closure: | Function | Closure signature | Each call to `next` | Fused? | `size_hint` | |---|---|---|---|---| | `iter::from_fn(f)` | `FnMut() -> Option<T>` | calls `f()` | no | default `(0, None)` | | `iter::successors(first, f)` | `FnMut(&T) -> Option<T>` | returns the stored item and computes its successor | yes | `(1, None)` or `(0, Some(0))` | Both have been stable since Rust 1.34 and live in `core::iter`, so they work in `no_std` code too. ## from_fn: the closure is next With `from_fn`, the closure's **captured variables** take the role of the struct's fields. For a paginated API client the state is the cursor of the next page and an iterator over the records already fetched: ```rust fn records() -> impl Iterator<Item = u32> { let mut buf = Vec::new().into_iter(); let mut cursor = Some(0); std::iter::from_fn(move || loop { if let Some(r) = buf.next() { return Some(r); } let page = fetch_page(cursor?); // None: no more pages cursor = page.next_cursor; buf = page.records.into_iter(); }) } ``` Points an interviewer looks for: - **`move` is required here.** Without it the closure borrows `buf` and `cursor`, which die when `records` returns, and rustc reports E0373, "closure may outlive the current function", suggesting `move`. - **It is exactly lazy.** A page is fetched only when the buffer is empty and a caller asks for the next record, so `records().take(3)` fetches two pages, not all of them. - **No promises.** std's documentation says `FromFn` makes no assumptions about the closure, so it does not implement `FusedIterator` and keeps the default `size_hint` of `(0, None)`. ## successors: each value from the previous one `successors` fits sequences where the next element is a function of the current one. Pages linked by a `next_cursor` are such a sequence: ```rust iter::successors(Some(fetch_page(0)), |page| page.next_cursor.map(fetch_page)) .flat_map(|page| page.records) ``` `successors` stores an `Option<T>`. Its `next` returns the stored item and, if it was `Some`, immediately calls the closure on a reference to it to compute and store the successor. Two consequences follow: 1. **It is one step ahead.** Handing out page 0 already runs the closure and fetches page 1. Running this pipeline with `.take(2)` — both records of page 0 — still makes two requests. For expensive steps such as network calls, that extra request matters. 2. **The first item is evaluated by the caller.** `Some(fetch_page(0))` is an ordinary argument, so page 0 is fetched when the iterator is built, before anyone calls `next`. Once the closure returns `None`, the stored option stays `None` and the closure is never called again, which is why `Successors` implements `FusedIterator`. ## Returning these iterators `from_fn` returns `FromFn<F>` and `successors` returns `Successors<T, F>`, where `F` is the closure's anonymous type. Because nobody can write that type, a function returns `impl Iterator<Item = T>`, and the caller sees only the trait. What the hidden type captures when the function borrows an argument is covered with return-position `impl Trait`. ## When a struct is the better tool Reach for a named struct when: - **The type must be named** — stored in another struct's field, used as an associated type such as `IntoIterator::IntoIter`, or mentioned in a public signature that callers may spell. - **Extra traits are honest** — `DoubleEndedIterator`, `ExactSizeIterator` or `FusedIterator` need an impl on a type you own. - **The size is known** — overriding `size_hint` lets `collect` pre-allocate. - **Clone and Debug matter** — `FromFn<F>` is `Clone` only when the closure is, and its `Debug` output is just `FromFn`, which shows nothing about the cursor. std's own comment on `successors` says it returns a named type rather than `impl Iterator` precisely so it can be `Clone`. - **The iterator has its own API** — a `cursor()` accessor to resume a paginated walk later, or a custom `Debug`. For a short-lived, private sequence inside one function, `from_fn` or `successors` is shorter and just as fast: each compiles to a call of the closure, and the optimiser usually inlines it.
- How many fetches does iter::successors make for the first two records in that pipeline, and why?Two. Page 0 is fetched when `Some(fetch_page(0))` is evaluated as the argument, and `successors` computes page 1 as soon as it hands out page 0, because it stores the successor eagerly. The from_fn version fetches page 1 only when a caller asks for the third record.
- Why does from_fn not implement FusedIterator even when the closure always returns None after the end?std cannot see what the closure does, so `FromFn` conservatively makes no promise. If the caller needs the guarantee, it calls `.fuse()`, or the author writes a struct that implements `FusedIterator` honestly.
- from_fn needs no move because the closure only runs inside the function.
- successors calls the closure only when the next item is requested.
- You can return FromFn<F> by name once you know the closure's type.
- from_fn implements FusedIterator, so it never resumes after None.
- Closure-based iterators are slower than a hand-written struct.