Skip to content

Filter and Transform a Borrowed Collection

The Course
•
34 min study

A report usually answers a question about some of the records: which books are still pending, which titles start with R. You could write a for loop that tests each record and pushes the winners into a new vector. Iterator adapters say the same thing as a pipeline: start with every item, keep the ones that pass a test, transform what is left, and gather the result. Each step has one job, so the reader can see the question the code answers.

iter() creates an iterator over shared references to a collection's items. An iterator hands out one item at a time. filter keeps items for which its closure returns true, and map transforms each item that reaches it. These adapters are lazy: building the chain does no work. A consumer such as collect pulls items through the chain one by one, and only then do the closures run.

Because iter() borrows, the chain cannot change or move the collection, and the collection is still yours when the chain finishes. Here the items are &Book. The filter closure receives a reference to each item, and map receives the surviving &Book and selects its title. Field access works through references with the same dot syntax.

Closures: functions written where they are used

Every adapter takes a closure, so read one closely first. A closure is a function without a name, written inline: parameters between bars, then the body. These two do the same job:

Rust
fn is_long(pages: u32) -> bool { pages > 300 }
let is_long = |pages: u32| pages > 300;

The closure usually leaves out the types, because the compiler infers them from how it is used: in .filter(|book| !book.finished), book is a &&Book without being told. A body longer than one expression goes in braces, and the last expression is the result, as in a function. ||, with nothing between the bars, is a closure with no parameters.

What a fn cannot do is see the variables around it. A closure can: it captures them. Here is_long uses limit from main, and describe calls is_long:

A closure captures a local variable Rust
fn is_long_fn(pages: u32) -> bool {
    pages > 300
}

fn main() {
    let limit = 300;
    let is_long = |pages: u32| pages > limit;
    let describe = |pages: u32| {
        let size = if is_long(pages) { "long" } else { "short" };
        format!("{pages} pages: {size}")
    };
    println!("{}", is_long_fn(450));
    println!("{}", is_long(450));
    println!("{}", describe(120));
    println!("Limit still readable: {limit}");
}
Text
true
true
120 pages: short
Limit still readable: 300

Try the same with a nested fn is_long(pages: u32) -> bool { pages > limit } inside main and the compiler refuses with error[E0434]: can't capture dynamic environment in a fn item, and suggests the closure form. That is the whole reason adapters take closures: the test can use a threshold, a search word or a map from the code around it.

A closure that only reads a variable captures it by shared reference, so the usual borrowing rules apply. limit can still be read after the closure, as the last line shows. Changing it while the closure is still to be used is refused:

Rust
let mut limit = 300;
let is_long = |pages: u32| pages > limit;
limit = 400;                      // error[E0506]: cannot assign to `limit` because it is borrowed
println!("{}", is_long(350));

The compiler marks limit as borrowed by the closure and the later is_long(350) call as the reason the borrow is still alive. Move limit = 400; after the last call, or set the limit before creating the closure, and it compiles. The same holds in a chain: a closure passed to filter borrows the variables it reads until the chain is consumed.

Predict and run

Which title survives the filter? Can the original array still be read after collect?

Predict, then run Rust
struct Book {
    title: String,
    finished: bool,
}

fn main() {
    let books = [
        Book { title: String::from("Rust"), finished: false },
        Book { title: String::from("Patterns"), finished: true },
    ];
    let pending: Vec<&str> = books.iter()
        .filter(|book| !book.finished)
        .map(|book| book.title.as_str())
        .collect();
    println!("{}", pending.join(", "));
    println!("Stored: {}", books.len());
}
Check your prediction
Text
Rust
Stored: 2

Only Rust is unfinished, so it is the only record that reaches map. The result is a Vec<&str>: each element borrows a title that still lives inside books, which is why books.len() works afterward. Change the filter to book.finished without the ! and predict the first line. Only the selection stage changes; map and collect do the same work on different survivors.

Nothing happens until a consumer pulls

Laziness is easiest to believe when you watch it. The chain below prints from inside each closure. Predict the order of the lines: does every filter call happen before any map call?

Watch items move through the chain Rust
fn main() {
    let ids = [7, 3, 9];
    let chain = ids.iter()
        .filter(|id| {
            println!("filter {id}");
            **id != 3
        })
        .map(|id| {
            println!("map {id}");
            id * 10
        });
    println!("Chain built");
    let scaled: Vec<i32> = chain.collect();
    println!("{scaled:?}");
}
Text
Chain built
filter 7
map 7
filter 3
filter 9
map 9
[70, 90]

Chain built comes first: creating the chain ran no closures. Then each item travels the whole pipeline before the next one starts. Item 3 fails the filter, so map never sees it. This is why chains avoid intermediate vectors: no list of "filtered items" ever exists in memory.

Two details in that code are worth noticing. The filter closure receives a reference to the item, and the item is already a reference (&i32), so the test needs **id. And if you forget the consumer, the compiler warns you with unused Map that must be used and the note iterators are lazy and do nothing unless consumed. That warning usually means a missing collect, count, or for loop.

Borrow with iter, take with into_iter

iter() lends the items. into_iter() on a Vec hands over the items themselves, which is useful when you want to transform owned values and no longer need the original. After that, the vector is gone:

Rust
fn main() {
    let titles = vec![String::from("Rust"), String::from("Patterns")];
    let upper: Vec<String> = titles.into_iter()
        .map(|title| title.to_uppercase())
        .collect();
    println!("{upper:?}");
    println!("Stored: {}", titles.len());
}

This fails with error[E0382]: borrow of moved value: titles, and the compiler adds that into_iter takes ownership of the receiver. Choose the method from what you need afterward: keep the collection, use iter(); consume it, use into_iter(). A for loop over &titles calls iter() for you, and a loop over titles calls into_iter().

Read a chain from top to bottom

Write one adapter per line and read them as a sentence: "for each book, keep the unfinished ones, take the title, collect the titles". If one step needs a comment to explain it, give it a named function instead of a long closure.

Practice

Exercise

Your turn

From [(7, false), (3, true), (9, true)], where the second value means "finished", collect the IDs of finished entries into a Vec<u32>. Print the vector, which should be [3, 9], then show that the original array still has three entries.

Your working space Rust
fn main() {
    let status = [(7, false), (3, true), (9, true)];
    println!("{status:?}");
}
Hint 1: the idea

Filter pairs by their status, then select only the ID from each surviving pair. Borrow the array so you can still use it.

Hint 2: a first step

Start with status.iter().filter(|entry| entry.1). Field access reaches through the references, so entry.1 is the bool.

Worked solution
Run the solution Rust
fn main() {
    let status = [(7, false), (3, true), (9, true)];
    let finished: Vec<u32> = status.iter()
        .filter(|entry| entry.1)
        .map(|entry| entry.0)
        .collect();
    println!("{finished:?}");
    println!("Stored: {}", status.len());
}
Text
[3, 9]
Stored: 3

map reads entry.0 through a reference and copies the integer out, so the result owns its IDs and borrows nothing from status. Compare that with the predict example, where Vec<&str> kept borrowing the titles. The next lesson replaces collect with consumers that answer a question without building any vector.

Was this article helpful?

Your response is saved on this device.