Skip to main content

Iterators and closures

Iterators in Rust are lazy: nothing happens until something consumes them. You build a pipeline with `map`, `filter`, `take`, and friends, and it only runs when you call `collect`, `sum`, or use it in a `for` loop.

Closures use pipe syntax: `|x| x * 2`. They capture variables from the surrounding scope, and the compiler works out whether that capture needs to borrow or move.

The payoff is that a long chain compiles down to roughly the same machine code as a hand-written loop. The abstraction is free.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust