Lifetimes and data flow.
Read reference relationships, captured context, and lazy iterator pipelines.
The idea behind the syntax.
A lifetime annotation describes how references relate to one another; it does not keep an object alive longer. In a function that returns one of two borrowed strings, the signature must tell the compiler which input lifetimes constrain the output. Often Rust infers this relationship, but an explicit annotation becomes necessary when several borrowed sources could be involved. The owner still decides when the underlying data is dropped.
Closures are anonymous functions that can capture values from their surrounding scope. A closure may borrow, mutably borrow, or take ownership of a captured value depending on what its body needs and whether move is used. Iterators are values that yield a sequence one item at a time. Adapters such as map and filter describe a pipeline lazily; a consumer such as collect or sum drives it.
What Rust is checking.
The traits Fn, FnMut, and FnOnce describe how a closure can be called based on its captures. A closure that consumes a captured owned value may only be callable once. A closure that mutates captured state needs mutable access. These are ownership rules applied to a compact function-like value, not a special exception to them.
An iterator's next method returns Option<Item>, signalling either another item or the end. Adapter chains can be efficient because they avoid intermediate collections until a consumer asks for results. But a long chain with hidden side effects can be harder to reason about than a loop. Read each stage by writing down the item type it receives and the item type it produces; then check what ownership is transferred along the pipeline.
See the rule in context.
Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.
Lifetimes & borrowed returns
Lifetime annotations describe relationships between borrows; they do not extend how long a value lives. When a function may return a reference into either of two inputs, an explicit lifetime can say that the result is usable only while the necessary input borrows remain valid. Many common signatures use lifetime elision rules and need no annotation. An owned return is often simpler when the result must live independently. A static string literal is valid for the entire program; a borrowed local String is not.
fn longer<'a>(left: &'a str, right: &'a str) -> &'a str {
if left.len() >= right.len() {
left
} else {
right
}
}
fn main() {
let first = String::from("compiler");
let second = String::from("cargo");
println!("{}", longer(&first, &second));
}compiler
- The same lifetime parameter connects both input references and the output.
- The annotation does not allocate or prolong either String.
- This comparison uses byte length as its explicit metric.
The boundary: Adding static to an error message about lifetimes is rarely a legitimate fix. Determine who owns the referenced data.
Closures & captured values
A closure can capture surrounding values by shared borrow, mutable borrow, or ownership. Rust infers the least demanding capture that fits the body, while move transfers captured values into the closure. Fn, FnMut, and FnOnce describe how a closure can be called: a consuming closure may be callable only once, while a read-only one can often be called repeatedly. Capturing ownership does not by itself mean a closure must be FnOnce-only; what the body does with the captured data matters.
fn main() {
let threshold = 10;
let large = |value: &i32| *value > threshold;
let values = [4, 12, 20];
let selected: Vec<_> = values.into_iter().filter(large).collect();
println!("{selected:?}");
}[12, 20]
- The closure borrows threshold for its comparison.
- filter asks the closure whether each item should remain.
- collect materializes a new vector.
The boundary: A move closure moves captured values, but can still implement Fn if it only reads its owned captures.
Iterators & lazy pipelines
An Iterator produces a sequence of optional next items. Adapters such as map and filter are lazy: they describe work that runs when a consumer requests elements. Consumers include sum, count, fold, collect, and a for loop. iter borrows elements, iter_mut borrows them mutably, and into_iter usually consumes the collection. Iterator chains can be concise, but a normal loop is often clearer when the work has multiple state changes or complex early exits.
fn main() {
let values = vec![1, 2, 3, 4];
let total: i32 = values.iter().filter(|&&n| n % 2 == 0).map(|&n| n * n).sum();
println!("total={total}, retained={}", values.len());
}total=20, retained=4
- iter preserves the vector.
- filter receives a reference to the iterator item, producing the double-reference pattern here.
- sum drives the lazy chain.
The boundary: A lazy map whose result is never consumed does not run the intended per-element work. Use for_each or a loop for deliberate side effects.
Keep this model.
Lifetimes describe borrowed relationships, closures carry context under ownership rules, and iterators make a sequence of transformations explicit.