expression

Iterator laziness — when does work happen?

Constructing an adapter normally does not traverse its source. Pulling items requests work as needed. A take limit can prevent evaluating the remaining inputs; do not rely on side effects in adapters being executed for every possible item. Expected stdout (not executed): ready visit 10 visit 11 [11, 12] Common mistake: Expecting a map closure to execute when the adapter is merely created.

Formal Syntax & Structure

rust syntaxrust
source.map(transform).take(n).collect::<Vec<_>>()

Working Example

Example Snippetrust
fn main() {    let pipeline = (10..14).map(|n| { println!("visit {n}"); n + 1 });    println!("ready");    let values: Vec<_> = pipeline.take(2).collect();    println!("{values:?}");}
Rust Reference