MARY.WIN

RUSTY — LARAVEL TO RUST — 10

Collections
and iterators

Choose between observing, changing, and consuming a collection.
Tutorial 10 of 16 in From Laravel to Rust. Before you start: Borrowing and Option.

Which iterator lets the palette keep its actions, and which consumes them? In examples/src/bin/ep10.rs, actions.iter() creates borrowed title views. actions.iter_mut() changes the titles. actions.into_iter() transfers the titles into a new vector.

Read the item type at each stage. Shared references allow inspection. Mutable references allow changes through exclusive access. Owned Action values allow the closure to move out each title.

main() starts with the enabled title tests and the disabled title deploy. Predict the borrowed list before mutation. Then predict the owned title list after the uppercase loop.

This lesson covers three ways into a Vec, iter(), iter_mut(), and into_iter(), and what each one hands to the steps of a chain. It also covers laziness, ordering, and what happens to errors inside a pipeline. It leaves out writing your own iterator. It assumes Tutorials 3 and 6. If you use Laravel collections, the method names will look familiar: filter, map, collect.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/ep10.rs)

#[derive(Debug)]
struct Action { title: String, enabled: bool }

fn main() {
    let mut actions = vec![
        Action { title: "tests".into(), enabled: true },
        Action { title: "deploy".into(), enabled: false },
    ];

    let visible: Vec<&str> = actions.iter()
        .filter(|action| action.enabled)
        .map(|action| action.title.as_str())
        .collect();
    assert_eq!(visible, vec!["tests"]);
    println!("{visible:?}");

    for action in actions.iter_mut() {
        action.title.make_ascii_uppercase();
    }
    assert_eq!(actions[0].title, "TESTS");

    let titles: Vec<String> = actions.into_iter()
        .map(|action| action.title)
        .collect();
    assert_eq!(titles, vec!["TESTS", "DEPLOY"]);
    println!("{titles:?}");
}

Make the two predictions above before you run it, the borrowed list before mutation and the owned title list after the uppercase loop, and then compare them with the two lines it prints:

TERMINAL
cargo run --quiet --bin ep10
["tests"]
["TESTS", "DEPLOY"]

The view that was finished in time

visible owned none of the titles it held. It was a Vec<&str> with one element, tests, and those five letters still belonged to the first Action in actions, which visible pointed into the way a library card points at a book still on the shelf. It was checked by one assert_eq!, printed as ["tests"], and not mentioned again. In the next statement a for loop asked actions for a mutable reference to every action and uppercased both titles, and the compiler allowed it, because the last use of visible was already behind it.

Sometimes you want three different things from one list, a view of it, an edit to it, and its contents, and the three chains look alike. Thankfully, the first method in each chain says which one you're getting, and the item type says what each step receives. Take another look at Example 1 and read it as three passes.

First pass: observe. actions.iter() yields shared references to the actions. .filter(|action| action.enabled) keeps the enabled action, .map(|action| action.title.as_str()) borrows its title text, and collect() stores that view in visible: Vec<&str>. The & in that type is the point: the output is a collection of borrowed views. The first print is ["tests"].

A borrowed view ties the output's validity to the original data. If you wanted to keep these titles after dropping or consuming the actions, you'd need owned strings or another ownership arrangement. Here you don't, because the last use of visible is its println!, before the iter_mut() loop. The shared references are no longer needed when mutation starts, and Rust can end the relevant borrow at that final use without requiring a separate block.

Second pass: change. actions.iter_mut() yields mutable references to the actions. The loop calls action.title.make_ascii_uppercase() for each one, and the strings become TESTS and DEPLOY. The vector still owns both actions.¹ A for loop is appropriate here, because the purpose is an effect on each item, and there's no reason to disguise mutation as a mapping operation that creates an unused iterator.

Third pass: transfer. actions.into_iter() consumes this owned vector. The closure .map(|action| action.title) receives owned actions and moves out their title strings, and titles: Vec<String> then owns those strings. The final print is ["TESTS", "DEPLOY"]. A later use of the consumed actions binding would be rejected.

No title is cloned, because ownership is being transferred. That is only the right choice if you're finished with the original records. Adding clone to make a later use compile might be acceptable for a small UI snapshot, or it might hide an unclear data flow; ask which representation needs to survive.

Read the three entrances as verbs: iter observes, iter_mut changes through borrowed access, and into_iter consumes this owned collection.²

When does a chain run?

Iterator adapters are lazy. Constructing a map chain does not necessarily execute the closure. Something has to consume the iterator, such as collect, a loop, or another consuming operation, which means code that builds a chain solely for its side effects can do nothing at all. That is one more reason the second pass is a for loop.

Comparisons with Laravel need care here. Ordinary Collection operations and LazyCollection operations do not have identical evaluation behavior. Similar method names are a useful bridge, not a promise that evaluation timing is the same.

A pipeline still needs a contract

There are two things worth stopping for. First, order. A vector provides a sequence. A hash map should not be used as a source of stable presentation order without an explicit ordering step. If a command palette or an exported report needs deterministic output, choose a suitable ordered structure or sort the result.

Second, failure. Suppose each title must be parsed and the parser returns Result, and someone writes filter_map with .ok() because it reads well and the types line up, which, for a deliberately best-effort view where a skipped row is a shrug, is correct, and which, for an import or a configuration file where a skipped row is a missing record, is a policy nobody chose, and both versions are one line and discard every error.

You can also collect an iterator of Result values into Result<Vec<_>, _>, which returns an error instead of silently throwing failures away. Decide whether the operation stops at an error, accumulates errors, or skips rejected items with a report. Fluent syntax should make that policy visible.

So all three passes run and both lines print. Now find one collection pipeline in your Laravel application. Is its result a view of the original models or an independent copy? After the pipeline, does anything edit the originals? Would the result be expected to notice?

Testing

Start with the first pass. Move the println! of visible below the mutation loop. Now the program needs the shared references across a mutable access, and the compiler rejects that arrangement. The problem is a conflicting use, not an arbitrary dislike of iterator syntax. Put the line back before you go on.

Then the exercise. Change visible to Vec<String>, and clone only the enabled titles while collecting the first result. Predict the snapshot after the original action titles are uppercased, and make that prediction before you move the snapshot's print below the mutation loop.

Once you've predicted, compare. The owned snapshot remains ["tests"] while the source title becomes TESTS, and an assertion on both values checks their independence. Next, build a map chain without consuming it and check whether its closure runs; a loop or collect() supplies the consumption. Finally, add another enabled action and assert the output order you intend.

TL;DR

iter() produces borrowed views, iter_mut() changes the stored items through exclusive borrowed access, and into_iter() consumes the collection and hands its items over as owned values. The item type at each stage tells you which one you have, and a borrow can end at its last use. Adapters are lazy until something consumes them. Order and error handling are part of a pipeline's contract and belong where a reader can see them.

¹ make_ascii_uppercase changes ASCII letters. It does not implement every Unicode casing rule, and its name says as much.

² The exact yielded type depends on the receiver and the implementation, so inspect the type when in doubt. Don't infer ownership solely from a method name seen on a different type.

The sources.

Every program, its output and every compiler message were recorded on rustc 1.100.0 on 2026-11-20. Each page lists what was not checked.

Rust Book, Processing a Series of Items with Iterators; standard-library Iterator and IntoIterator documentation; Laravel 13 Collections and Lazy Collections. All action-list examples are original.

NOT CHECKED — 4
  • Moving the println! of visible below the mutation loop: the lesson repeats the claim that the compiler rejects this, but the change was not run for this edition.
  • A later use of actions after into_iter() would be rejected: not run.
  • The exercise (an owned snapshot, an unconsumed map chain, another enabled action and its order) was not run.
  • The comparison of Laravel's Collection and LazyCollection evaluation follows the Laravel 13 documentation. No Laravel application was run.