2026-08-20
iterator.rs
fn main() {
let v = vec![1, 2, 3];
let mut iter = v.iter().map(|x| {
println!("mapping {}", x);
x * 2
});
println!("created");
let first = iter.next();
println!("{:?}", first);
}
What order do the lines print in?
Answer
created, then mapping 1, then Some(2). Rust iterators are lazy — .map() doesn't run its closure until something actually pulls a value out via .next(). Creating the iterator does no work; only consuming it does.