Why does printing a title make the next print fail to compile? In examples/compile-fail/fail01.rs, main() gives an Action to preview(). The next line tries to print action.title. We will identify the ownership transfer, then change preview() so the caller can still read the title.
The comparison starts with object assignment in examples/php-comparison.php. PHP object variables can identify the same object. The Rust example has a different question: does preview() receive ownership of the Action, or temporary access to it? Read the parameter type to answer that question.
The PHP example prints “Run focused tests.” $action and $other identify the same Action object. Assigning $action to $other copied the object identifier. Setting $other->title therefore changes the title observed through $action.
That is different from saying PHP passes everything by reference. A PHP reference made with an ampersand aliases variable storage. Ordinary object assignment does not make those variables aliases: assigning a new object to $other would not replace the object identified by $action. Keep that distinction, because familiar words can carry the wrong explanation into another language.
This lesson covers one thing: what a Rust function signature says about who keeps a value after the call. We'll look at PHP object assignment, a Rust function that takes its argument by value, the compiler's refusal, and the borrowed version that repairs it. It leaves out the full borrowing rules (Tutorial 3) and lifetimes (Tutorial 5). It assumes you can read a PHP class and can run cargo and rustc. If you already know why a String-holding struct can't be used after it is passed by value, skip to Testing.
Take a look at Example 1.
Example 1. PHP object assignment
struct Action { title: String }
fn preview(action: &Action) -> &str {
&action.title
}
fn main() {
let action = Action { title: "Run tests".into() };
assert_eq!(preview(&action), "Run tests");
println!("preview: {}", preview(&action));
println!("still available: {}", action.title);
}
Run it from the examples/ directory.
Expected output:
cargo run --quiet --bin ep01
preview: Run tests
still available: Run testsBoth lines read the same Action, and the second one reads it after preview has been called twice. To see why the signature is written that way, start where this page started, with PHP.
Two variables, one object
Take a look at Example 2, the PHP comparison described at the top of this page.
Example 2. Two variables, one object (examples/php-comparison.php)
<?php
final class Action
{
public function __construct(public string $title) {}
}
$action = new Action('Run tests');
$other = $action;
$other->title = 'Run focused tests';
echo $action->title, PHP_EOL;
There are two lines to read. $other = $action copies the object identifier, so $other and $action identify the same Action. $other->title = 'Run focused tests' then changes the one title both variables reach, which is why the last line prints “Run focused tests” and not “Run tests”. Nothing in the listing made a second Action with an independent title.
What does the signature promise?
The function preview accepted an Action by value. Its body was one line, a println! of the title, and its parameter list held no ampersand. It regarded the Action as its own from the moment of the call, the way a dog regards whatever has been dropped on the kitchen floor. main passed the Action in, and on the next line asked for the title again. The compiler reported E0382.
Take a look at Example 3, which is that program.
Example 3. A function that takes its argument (examples/compile-fail/fail01.rs, compiler refusal)
struct Action { title: String }
fn preview(action: Action) {
println!("{}", action.title);
}
fn main() {
let action = Action { title: "Run tests".into() };
preview(action);
println!("{}", action.title);
}
Compile it. The diagnostic is E0382, and it reads “borrow of moved value”:
rustc --edition=2024 compile-fail/fail01.rs
error[E0382]: borrow of moved value: `action`
--> compile-fail/fail01.rs:10:20
|
8 | let action = Action { title: "Run tests".into() };
| ------ move occurs because `action` has type `Action`, which does not implement the `Copy` trait
9 | preview(action);
| ------ value moved here
10 | println!("{}", action.title);
| ^^^^^^^^^^^^ value borrowed here after move
|
note: consider changing this parameter type in function `preview` to borrow instead if owning the value isn't necessary
--> compile-fail/fail01.rs:3:20
|
3 | fn preview(action: Action) {
| ------- ^^^^^^ this parameter takes ownership of the value
| |
| in this function
note: if `Action` implemented `Clone`, you could clone the value
--> compile-fail/fail01.rs:1:1
|
1 | struct Action { title: String }
| ^^^^^^^^^^^^^ consider implementing `Clone` for this type
...
9 | preview(action);
| ------ you could clone this value
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0382`.Read preview(action: Action) first. The parameter has type Action, with no &. This Action contains an owned String and does not implement Copy, so the call preview(action) moves ownership into the parameter. The later println! tries to borrow the moved value through action.title, and that borrow is what the compiler reports: “value borrowed here after move”, on line 10.
The body only prints, and that does not revise the contract. Rust checks the interface we wrote. A caller should not have to read a function's implementation to learn whether passing a value gives it away.
Borrowing the action
Sometimes a function only needs to look at a value while it runs, and handing over the whole value means the caller can't use it again. Thankfully, there's a smaller contract. preview only needs to read Action.title, so change the parameter from Action to &Action. That change is Example 1.
There are three new pieces, in the order they appear. The & on the parameter says preview borrows the Action. The return type &str, with the body &action.title, hands back a borrowed view of the title text. And the & in preview(&action) at each call site supplies a shared reference while main keeps ownership. Because main keeps the Action, both calls read the same text, the assert_eq! checks that the returned text is Run tests, and the last line can still print action.title.
Put Example 2 beside Example 1. The PHP variables are “same object”; preview(&action) is “borrowed access.”
Example 3's first note suggested exactly this borrow. Its second note, the one that begins “if Action implemented Clone”, offers another way out. If we derive Clone for Action and keep the by-value preview, passing action.clone() gives preview another owned value, and that is, depending on whether anything later needs two independent values and on whether the copy was something the operation wanted or only a way past E0382, either the correct contract or a way of hiding that preview asked for more responsibility than it needed, and for a function that prints one title it is the second.
I do not want a rule that says “never clone.” If you're unsure, I'd ask for the reason for the copy first. In a command palette, preparing a launch request may intentionally copy the chosen arguments so later edits cannot change the queued intention. A preview has no such requirement.
The project we are building
The series builds a palette with two entries, Run tests and Clear cache. A user searches, selects an entry, and stages a launch request. The catalog remains editable. The staged request must preserve what was selected. Search inspects an entry, rename edits one, prepare constructs independent request data, and stage transfers the request into a collection. Those are four different relationships, and we are going to make them visible in signatures.¹
So the borrow compiles, and the lesson could stop here. But look at your own controllers and services for a moment. When one of them receives an object, does it mean to look at it, to change it, or to keep it? Does the method's signature say which? Would the caller be surprised by the answer?
Testing
Example 1 carries its own test. assert_eq!(preview(&action), "Run tests") checks the borrowed text, and the final println! reads action.title after both calls. Example 3 is the counter-case: the by-value signature followed by a later read, which the compiler refuses.
Now predict before you change anything. In ep01.rs, change preview() to take an owned Action, print the title, and return the Action. In main(), bind that return value before the later print. Can the returned binding be used? Decide before you read the next paragraph.
It can. Ownership moves into preview() and then back to the caller, and the new binding owns the Action. That round trip adds a handoff to an operation that only needs inspection, so put the &Action version back once you have compared the two.
For a second prediction, take Example 3 and remove its last println!. Look at where the compiler put its error label: “value borrowed here after move” sits on the later use, and preview(action) only gets “value moved here”. The move was never the conflict; using the old binding after it was.
Last, close the file and explain from memory why main() can print action.title after the call. Then compare your answer with the signature.
TL;DR
PHP object assignment copies an identifier, so two variables can identify one object. A Rust parameter of type Action takes ownership of the value, and the caller's binding cannot be used afterward; the compiler reports E0382. A parameter of type &Action borrows, and the caller keeps the value. Cloning gives the function a second owned value and returning ownership hands the value back; each answers a different requirement, and a preview needs neither. Next we follow one request from construction to a pending list to cleanup, naming its owner at each step.
¹ One more PHP detail. An array of scalar strings normally behaves as an independent value under ordinary assignment and later edits. An array containing objects still contains identifiers for those same objects; copying the array does not recursively copy the object graph.
Practise it with tuitor (alpha)
This tutorial has a tuitor pack, laravel-to-rust-01. 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.