When does a staged request get cleaned up? In examples/src/bin/ep02.rs, main() creates one Request. The stage() function moves that request into pending. We will follow the owner through both moves, then predict when Request::drop() prints its cleanup message.
Follow three storage locations in the source: the local request in main(), the request parameter in stage(), and the element in pending. Each move ends ownership at the previous location. The vector owns the request after pending.push(request).
The Request struct contains a title: String field. Its Drop implementation prints the title when the request is dropped. This explicit implementation makes cleanup observable; ordinary structs also drop their owned fields without requiring a custom Drop implementation.
This lesson covers where one value lives at each step of a small program: a local variable, a function parameter, an element of a Vec, and then nowhere. We'll use Drop to make the last step print. It leaves out borrowing (Tutorial 3) and shared ownership with Arc (Tutorial 12). It assumes Tutorial 1. In that tutorial two PHP variables identified the same object, because assignment copied the object identifier. Rust asks a question PHP assignment leaves unstated: which one place owns the value right now?
Take a look at Example 1.
Example 1. Complete example (examples/src/bin/ep02.rs)
struct Request { title: String }
impl Drop for Request {
fn drop(&mut self) {
println!("cleanup: {}", self.title);
}
}
fn stage(request: Request, pending: &mut Vec<Request>) {
pending.push(request);
}
fn main() {
let request = Request { title: "Run tests".into() };
let mut pending = Vec::new();
stage(request, &mut pending);
assert_eq!(pending.len(), 1);
println!("pending: {}", pending[0].title);
drop(pending);
println!("finished");
}
Before you run it, predict where cleanup: Run tests falls among the three lines it prints. Then run it.
Expected output:
cargo run --quiet --bin ep02
pending: Run tests
cleanup: Run tests
finishedWhere does the request live?
The Request began the program in a local variable named request. It held one field, a String reading “Run tests”, and a five-line impl Drop that printed on the way out. The local understood itself to be where the Request lived. It was passed to stage, and stage passed it to push. By the fourth line of main the only place the Request could be reached was pending[0].
Sometimes you read an application and cannot say which variable, field or collection holds a value at a given line. Thankfully, Example 1 is small enough to name the owner at every step, and each move ends ownership at the previous location. Here are the four states, with the labels the rest of this lesson uses.
Line in ep02.rs |
Where the Request is |
|---|---|
let request = Request { title: "Run tests".into() }; |
main::request |
stage(request, &mut pending); |
stage::request |
pending.push(request); |
pending[0] |
drop(pending); |
dropped; cleanup: Run tests prints |
The table uses the program's actual stages. At no row are there two owners.
Now read the listing against the table. In main(), the local request owns the new Request. The call stage(request, &mut pending) transfers that value into stage()’s parameter. Inside stage(), pending.push(request) transfers the value into the vector. Back in main(), drop(pending) consumes the vector, and dropping its element calls Request::drop(), which prints cleanup: Run tests.
Returning from stage() does not print cleanup, because the parameter’s value has already moved into pending. Two lines check the table while the program runs: assert_eq!(pending.len(), 1) confirms the vector holds one element after stage returns, and the later pending[0].title read shows that the vector still retains the request before drop(pending).
What a move promises
A move is a promise about the language, and it makes no promise about the machine. Moving a String does not require duplicating its text buffer, but I'd avoid building the explanation on a particular stack-and-heap drawing. The promise is that the old place is no longer usable as an independent owner of the moved value.¹
“All values move” needs one qualification. A value whose type implements Copy can be copied implicitly; small identifiers such as u32 usually fit that model, and a String does not. The distinction follows the type. It does not follow the variable's name, its printed size, or whether you wrote mut.
You can also keep an identifier and give away the thing it names. Copy a request's numeric ID into a log message and move the request into pending. The ID cannot keep a running task alive, restore a removed task, or prove that a caller may access it.
What cleanup can promise
The claim this program supports is local: when the vector is normally dropped, its owned Request is dropped, and the cleanup line prints. That is not a crash recovery protocol. Process termination, abort behavior, deliberately leaked values, and external systems all complicate the story, and a destructor is not the place to pretend a remote service has acknowledged a cancellation or a child process has finished. Closing a panel might drop a UI object; that does not necessarily stop work it started. Later tutorials signal work to stop and wait for it.
When is a copy the right decision?
Return to the palette. The catalog is editable, but a selected launch request should keep the arguments the user saw at selection time. That requirement calls for independently owned data, and cloning a Vec<String> supplies it: another vector, with cloned strings.
The spelling .clone() on its own does not tell you that, since a clone of an Arc<T>, which we meet in Tutorial 12, is another ownership handle to the same allocation, and a clone of a Vec<String> is new strings, and the two lines look alike on the screen and are distinguished by the type to the left of the dot, which is the thing to read.
So the program runs, and every row of the table has an owner. Now ask it of a request in your own application. Must it survive the catalog entry being removed? Must it keep the old arguments? “The compiler wanted a clone” tells the next maintainer almost nothing. What would you write in the review instead?
Testing
Example 1's assert_eq!(pending.len(), 1) is the test of the main claim: after stage returns, the request is in the vector, not gone.
Now predict before you change anything. In ep02.rs, move println!("finished") above drop(pending). Write down the three output lines in the order you expect, and decide before you read the next paragraph.
The order becomes pending: Run tests, finished, then cleanup: Run tests. Calling drop(pending) consumes the vector at that point, so the cleanup line moves with the call.
Next, try to read request.title after stage(request, &mut pending). That binding has moved; it is the same move followed by a later read that produced E0382 in Tutorial 1. The title is available through pending[0].title, where the value now lives.
To explore independent values, remove the custom Drop implementation, derive Clone for Request, and clone the request before staging it. The two values then own separate title strings.
Last, close the file and reconstruct the request's owner at each call: main::request before stage(), pending[0] after it, and drop(pending) ending that local lifecycle. Compare your reconstruction with the three terminal lines.
TL;DR
A value has one owner at a time, and the owner changes: here from main::request, to stage::request, to pending[0]. Dropping the vector drops its elements. A move is a statement about which place may use the value, and Copy types are the exception to it. Drop shows ordinary scope cleanup and nothing about crashes or remote systems. Copy when independent data is part of the requirement, and say which requirement. Next: what a function does when it only needs temporary access.
¹ The compiler is free to optimize how the machine carries out that promise.
Practise it with tuitor (alpha)
This tutorial has a tuitor pack, laravel-to-rust-02. 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.