Closures and iterators
Iterators are where idiomatic Rust lives. A chain of map and filter does one pass, allocates
nothing, and is checked like the loop it replaces.
This is the longest chapter in the book on purpose: the iterator adapters are the vocabulary you read in everybody else’s code.
Articles
Section titled “Articles”Nothing published in this chapter yet — all 23 articles are still to come.
Coming up (23)
- What is a closure?an anonymous function that keeps its environment
- What are the Fn, FnMut, and FnOnce traits?how a closure captures, turned into a trait
- How to choose between Fn, FnMut, and FnOnceread, mutate, or consume
- How closures capture their environmentby reference, by unique borrow, or by move
- What is the move keyword in closures?taking ownership so the closure can outlive the scope
- How to pass a closure to a functionimpl Fn versus a generic parameter
- How to return a closure from a functionimpl Fn, Box<dyn Fn>, and when each works
- What is the Iterator trait?one method to implement, dozens you get free
- How to use map, filter, and collectthe chain, and why nothing runs until collect
- What does collect do, and how do you annotate its type?it builds whatever you name
- How to use filter_mapwhen the filter and the map are the same step
- How to use enumerate and zipthe index, and pairing two sequences
- How to use fold and reducean accumulator, and the empty case
- How to use sum, count, min, and max on iteratorsand the Option that min returns
- What is the difference between iter, iter_mut, and into_iter?borrow, borrow mutably, or consume
- How to create a custom iteratorone method, and the loop-free caller
- What are lazy iterators?why the chain costs nothing until you ask
- How to chain iterator adapters efficientlyone pass, not one Vec per step
- How to find the first match in an iteratorfind, position, and stopping early
- How to use peekable iteratorsone token of lookahead
- How to flatten nested iteratorsflat_map, and the difference from map then flatten
- How to sort a collection of your own typeOrd, sort_by_key, and the allocation it avoids
- How to group values with iteratorsfold into a map, then read it back sorted