Iterators From Functions And Successors

Build iterators without a struct using std::iter::from_fn for closure state and successors for first-element-plus-step sequences like counters and Fibonacci.

RustData Integrity

Code

rustsnippet
26 lines
use std::iter;

fn main() {
    // from_fn:闭包即迭代器,状态装进闭包,返回 None 终止
    let mut page = 1;
    let pages = iter::from_fn(move || {
        if page > 3 {
            return None;
        }
        let current = page;
        page += 1;
        Some(format!("page-{current}"))
    });
    for p in pages {
        println!("{p}");
    }

    // successors:首元素 + 后继函数;checked_sub 在 0 之下自然收尾
    let steps: Vec<u8> = iter::successors(Some(3u8), |n| n.checked_sub(1)).collect();
    println!("{steps:?}");

    // 斐波那契:successors 携带状态元组滚动
    let fib = iter::successors(Some((1u64, 1u64)), |(a, b)| Some((*b, a + b))).map(|(a, _)| a);
    let first_five: Vec<u64> = fib.take(5).collect();
    println!("{first_five:?}");
}

How the snippet works

Count the function main as the entire surface area of Iterators From Functions And Successors.

Iteration happens inside for p in pages — everything outside it runs once.

Statements that matter

let fib = iter::successors(Some((1u64, 1u64)), |(a, b)| Some((*b, a + b))).map(|(a, _)| a);
let steps: Vec<u8> = iter::successors(Some(3u8), |n| n.checked_sub(1)).collect();
let first_five: Vec<u64> = fib.take(5).collect();

Interactive Tools for This Topic

FAQ

How do you run Iterators From Functions And Successors?
Execute it straight away — the program needs nothing beyond the runtime.