std-function

std::iter::from_fn — create a closure-driven iterator

Use a closure as the next operation when a dedicated struct is unnecessary. The wrapper cannot infer permanent exhaustion or a precise length from arbitrary closure behavior. Expected stdout (not executed): [2, 1, 0] Common mistake: Assuming None automatically fuses this iterator.

Formal Syntax & Structure

rust syntaxrust
pub fn from_fn<T, F>(f: F) -> FromFn<F> where F: FnMut() -> Option<T>

Working Example

Example Snippetrust
fn main() {    let mut remaining = 3;    let values: Vec<_> = std::iter::from_fn(|| { if remaining == 0 { None } else { remaining -= 1; Some(remaining) } }).collect();    println!("{values:?}");}
Rust Reference