MARY.WIN

RUSTY — LARAVEL TO RUST — 03

Borrowing:
passing values without losing them

Choose inspection, editing, and ownership deliberately.
Tutorial 3 of 16 in From Laravel to Rust. Before you start: Moving values through functions.

Which operation needs ownership of an action? In examples/src/bin/ep03.rs, matches() reads an action, rename() changes its title, and stage() retains a request. Their parameter types express three different access requirements.

Read the three parameter forms aloud: &Action is a shared reference, &mut Action is an exclusive mutable reference, and Request is an owned value. Match each form to the operation before inspecting its implementation.

matches() only reads Action.title. rename() replaces Action.title. prepare() copies the current argument strings into a new Request. stage() moves that request into pending. The catalog must remain editable after preparation.

This lesson covers three ways a function can receive a value: a shared borrow &T, an exclusive mutable borrow &mut T, and ownership T. We'll match them to four functions, matches, rename, prepare, and stage. It leaves out what to do when two borrows collide in one function (Tutorial 4) and interior mutability, which is a later design choice. It assumes Tutorials 1 and 2.

Take a look at Example 1.

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

struct Action { title: String, argv: Vec<String> }
struct Request { argv: Vec<String> }

fn matches(action: &Action, query: &str) -> bool {
    action.title.to_ascii_lowercase()
        .contains(&query.to_ascii_lowercase())
}

fn rename(action: &mut Action, title: String) {
    action.title = title;
}

fn prepare(action: &Action) -> Request {
    Request { argv: action.argv.clone() }
}

fn stage(request: Request, pending: &mut Vec<Request>) {
    pending.push(request);
}

fn main() {
    let mut action = Action {
        title: "Run tests".into(),
        argv: vec!["php".into(), "artisan".into(), "test".into()],
    };
    assert!(matches(&action, "TEST"));
    let request = prepare(&action);
    rename(&mut action, "Focused tests".into());
    action.argv.push("--compact".into());
    let mut pending = Vec::new();
    stage(request, &mut pending);
    assert_eq!(pending[0].argv, ["php", "artisan", "test"]);
    assert_eq!(action.argv.len(), 4);
    println!("catalog edited; request preserved");
}

Run it.

Expected output:

TERMINAL
cargo run --quiet --bin ep03
catalog edited; request preserved

The request that stayed behind

The Action in the catalog assumed anything prepared from it would follow its edits. It had a title and an argv of three strings. prepare read it through a shared reference and left with a Request holding its own Vec<String>. Then main renamed the Action and pushed --compact onto its argv, like a cook salting the pot after the plates have gone out. The Request in pending still held three arguments.

In PHP, a function receiving an ordinary object can mutate the same object without declaring an ampersand parameter. That is familiar and often useful, but it means three functions that do three different things to their input can share one signature. In Rust the signature can say which is which. Read Example 1 one function at a time.

  • matches(action: &Action, query: &str) borrows both inputs, and its lowercase comparison returns a bool. The caller still owns action.
  • rename(action: &mut Action, title: String) borrows the action exclusively. The assignment action.title = title moves the supplied string into the action.
  • prepare(action: &Action) -> Request reads the catalog entry through a shared reference. The expression action.argv.clone() creates the request's independently owned Vec<String>.
  • stage(request: Request, pending: &mut Vec<Request>) takes the request itself, and pending.push(request) moves it into the vector.

After prepare() returns, main() can rename the catalog entry, and it can append --compact to the catalog's arguments without changing request.argv. The two assert_eq! lines near the end check exactly that. The one on pending[0].argv expects php, artisan, and test; the one on action.argv.len() expects four arguments after the edit. Together they verify that the request kept the earlier three-argument snapshot, and the program prints catalog edited; request preserved only after both pass.¹

What does &mut mean?

It is tempting to read &mut as “please let me change this.” The stronger idea is exclusive access for the duration of that borrow: while the reference is live, Rust has to reason about any other access to the same place. Shared borrowing lets several readers inspect a value. Exclusive mutable borrowing lets one operation edit it with no overlapping incompatible access.

A mut binding and an &mut parameter are different things. The binding says the variable permits mutation. The reference expresses access granted to another operation. Adding mut everywhere does not create several compatible mutable borrows.

When does a borrow end?

Sometimes you want to read a field and then change the same struct a few lines later, and it looks as if the read should block the change until the closing brace. It doesn't. Take a look at Example 2, two lines that go inside main(), immediately before rename(&mut action, ...).

Example 2. A shared borrow that ends at its last use (insert before rename)

let title = &action.title;
println!("before: {title}");

The shared reference title is created on the first line and last used on the second. A reference's scope runs from where it is created to its last use, not to the closing brace of main, so by the time rename asks for exclusive access, nothing is reading through title any more.

Now keep let title = &action.title above rename() and move the println! below it. The later print needs the shared reference to stay valid across an exclusive mutable borrow of action, and that overlap is what the borrow checker refuses. Move the print back above rename() to end the shared use before the mutation. Tutorial 4 shows the compiler's full message for a shared reference held across a mutation.

The PHP side

You can design good PHP APIs with the same distinctions: separate queries from commands, use immutable values where appropriate, keep side effects visible in names. Rust adds compiler-checked distinctions to some of those choices. That does not make every permitted Rust program well designed or every PHP program careless.

What transfers from Laravel is the habit of asking for an operation's real responsibility, and in a Laravel application that question has, depending on whether the thing is a formatter or a policy or a queued payload and on what was convenient the day it was written, usually been answered by passing the larger object and trusting everyone to touch only their part, which works until someone doesn't.

So ask it out loud. Does a formatter need the whole application container? Does a policy need a mutable model? Does a queued payload need live service objects?

Testing

Example 1's two assert_eq! lines are the test of the main claim: the staged request still holds three arguments while the catalog entry holds four.

Now predict before you change anything. In ep03.rs, sketch a Request that borrows an argument slice instead of owning a Vec<String>. Could that borrowed request stay live across the later action.argv.push(...)? Which value owns the underlying argument storage? Decide before you read the next paragraph.

It could not. The borrowed request depends on the catalog's argument storage, which action owns, and retaining that shared view across the vector mutation is an incompatible access relationship, the same overlap as Example 2 with the print moved below rename(). The original owned request is what satisfies the requirement to preserve the selected arguments through edits.

As a separate change, make matches() accept the title as &str. That narrower input is enough for the existing comparison. Borrow the whole Action only when the operation needs that domain value.

Last, explain each signature in Example 1 without looking at it, then check yourself: matches() borrows to inspect, rename() borrows exclusively to edit, prepare() returns independent request data, and stage() takes ownership to retain it.

TL;DR

Borrow with & to inspect, borrow with &mut to edit exclusively, and take ownership to retain. prepare borrows the catalog entry and returns independent request data, so the catalog can change afterward, and the assertions check that the request did not. A borrow ends at its last use. Next: a shared reference that stays live across a vector mutation.

¹ If the arguments contained shared handles, their Clone implementations could preserve sharing. The test needs to reflect the actual field types; a method name is not a substitute for understanding the data.

Practise it with tuitor (alpha)

This tutorial has a tuitor pack, laravel-to-rust-03. tuitor is a command-line tutor for PHP and Laravel developers: tuitor check tests your own project against the lesson’s standards and names each one that isn’t met yet. tuitor is in alpha. The install command comes with its first public release.

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; standard-library String, Vec, Clone, and slice documentation.

NOT CHECKED — 1
  • That a Laravel application usually answers "what does this operation need?" by passing the larger object. This is an interpretive generalization in the Laravel paragraph, not a documented fact.