MARY.WIN

RUSTY — LARAVEL TO RUST — 04

The borrow checker
as design feedback

Separate choosing an entry from mutating the catalog.
Tutorial 4 of 16 in From Laravel to Rust. Before you start: Shared and exclusive borrows.

Can the palette remember a selected entry while appending to its list? In examples/compile-fail/fail04.rs, selected borrows actions[0]. The next line calls actions.push(...). A later print still needs selected, so the shared borrow overlaps the mutation.

The repair depends on what selection means. To remember the current entry after appending, this example can retain an index. To preserve the old text through edits, an owned string would serve a different requirement. Choose the retained information before changing the borrow.

Read the three relevant operations in order: borrow actions[0], push a second string, then print through the earlier reference.

Vec::push() takes a mutable borrow of actions. The selected reference requires shared access through the later print. Those borrows conflict. A push can also reallocate the vector’s element storage; retaining a reference to an old location would be unsafe. Spare capacity in one run does not make these overlapping borrows acceptable.

This lesson covers one borrow conflict, E0502, and three repairs for it: remember a fact instead of a reference, take an owned snapshot, or shorten the borrow. It leaves out runtime-checked sharing, which the lesson mentions and does not use. It assumes Tutorial 3, where a PHP function could mutate an object it received with no ampersand in sight, and where & and &mut went to different operations. Here two of those accesses meet in one function.

Take a look at Example 1.

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

fn main() {
    let mut actions = vec![String::from("Run tests")];
    let selected_index = actions.iter()
        .position(|title| title == "Run tests")
        .expect("seeded entry exists");

    actions.push(String::from("Clear cache"));

    let selected = &actions[selected_index];
    assert_eq!(selected, "Run tests");
    assert_eq!(actions.len(), 2);
    println!("selected: {selected}; entries: {}", actions.len());
}

It is the repair; the refusal it repairs is Example 2, below. Run Example 1 first.

Expected output:

TERMINAL
cargo run --quiet --bin ep04
selected: Run tests; entries: 2

The reference that stayed too long

The reference selected pointed at actions[0] and intended to go on pointing there. It was created on line 3 and used on line 5. Between them, on line 4, actions.push asked for the whole vector, storage included. The compiler reported E0502 and named all three lines.

Take a look at Example 2, which is that program.

Example 2. A reference held across a push (examples/compile-fail/fail04.rs, compiler refusal)

fn main() {
    let mut actions = vec![String::from("Run tests")];
    let selected = &actions[0];
    actions.push(String::from("Clear cache"));
    println!("selected: {selected}");
}

Compile it from the examples/ directory:

TERMINAL
rustc --edition=2024 compile-fail/fail04.rs
error[E0502]: cannot borrow `actions` as mutable because it is also borrowed as immutable
 --> compile-fail/fail04.rs:4:5
  |
3 |     let selected = &actions[0];
  |                     ------- immutable borrow occurs here
4 |     actions.push(String::from("Clear cache"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("selected: {selected}");
  |                          -------- immutable borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0502`.

Read the three labels from top to bottom. Line 3 is where the immutable borrow occurs. Line 4 is the mutable borrow, because Vec::push() takes &mut self. Line 5 is where the immutable borrow is used later. No single line is the problem; the problem is the first and third holding a shared borrow open around the second.

Replace the long borrow with the fact you need

Sometimes an operation has to remember which entry was chosen while the list changes underneath it, and holding a reference for that whole time is what the compiler refuses. Thankfully, the operation rarely needs the reference; it needs to know which entry. Go back to Example 1.

There are three steps. .position(...) returns the numeric selected_index, and the iterator's borrowed work finishes there, before actions.push(...). The push then mutates the vector while the program holds only that number. After the push, &actions[selected_index] creates a fresh reference into the current vector, and the program prints selected: Run tests; entries: 2 after both assertions pass.¹

In this small example an index is enough, because the list is only appended to; nothing reorders or removes earlier entries. Keep that assumption next to selected_index, because the next section takes it away.

When does the index stop working?

An index is not a permanent identity. If the collection can remove entries, insert before them, or reorder them, the same number may identify something else. In that application, store an ActionId and resolve it against the current catalog; resolution can fail if the item was removed, and that is a real possibility in the domain.

The compiler did make us say how long the access lasts and whether the storage it points into is still valid, but on the rest of it, on what a selection should mean after a sort, or which user owns an entry, or whether a request should preserve old data, or whether an index or a stable ID is the right thing to remember, it has no view at all, and those requirements stay with us.

Other repairs

You can also clone the selected title before the mutation, when the operation needs a snapshot of the old text. You can also end the borrow earlier, by finishing the reference's work sooner or putting it in a small scope. And when a method borrows a whole struct but needs one field, splitting the responsibility or borrowing disjoint fields can expose an independence the original API hid.

Requirement Repair
“Old title” Owned copy
“Current entry” Stable ID plus lookup
“Read during this call” Shorter borrow

Sometimes the data really is shared and mutable across independent owners, and a runtime-checked arrangement fits. I'd arrive there from the requirement, and not from a reflex to wrap the application in a lock.

A repeatable conversation

When the compiler complains, first identify the two incompatible operations. Ask which reference must stay valid and which mutation would interfere. Then say what the application needs to preserve: identity, contents, or access during one call.

So the index version compiles and its assertions pass. Now describe your own selection feature without mentioning Rust. After the user sorts the list, is the selection the same row or the same item? After the item is deleted, what is selected? Has anyone written that down?

Testing

Example 1's assertions protect the append-only assumption: selected must still be Run tests after the push, and the list must hold two entries.

Now predict before you change anything. In ep04.rs, replace actions.push(...) with an insertion at index zero. Which title will actions[selected_index] identify now? Decide before you read the next paragraph.

The remembered index is zero, so it now identifies the inserted Clear cache title, and the Run tests selection assertion fails. Nothing in the change holds a reference across the insertion; the failure is the assertion's. This is the negative control, and it shows where the index design stops meeting the requirement.

Repair that variation with a stable action ID and a fresh lookup after the insertion, and return Option when the ID is absent. For an editable catalog, write a test that selects an item, reorders the catalog, and resolves the same ID, then test deletion, so a stale selection cannot silently target a different action. Compare this with copying the old title: stable identity selects a current record, while an owned title preserves earlier text.

Last, state your own collection's allowed edits, and only then choose between an index, a stable ID, and an owned snapshot.

TL;DR

E0502 reports a shared borrow still in use across a mutable one. Remembering an index, taking an owned copy, and shortening the borrow each remove the conflict, and each makes a different promise. The index repair satisfies an append-only list; inserting at index zero can break the selection, and the assertion is what catches it. The compiler checks access; the assertions check the selection behavior. Next: lifetimes, which name the validity relationship directly.

¹ The .expect("seeded entry exists") call relies on main() creating the Run tests entry immediately before the lookup. A lookup driven by user input needs an explicit absence branch instead, and Tutorial 6 uses Option to represent it.

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, References and Borrowing and Storing Lists of Values with Vectors; standard-library Vec documentation.