Module 9 · Lesson 5 of 112

The three ownership rules and moves

Trace ownership of a Rust String through assignment, function calls, and returns, and diagnose a use after move.

  • Beginner to advanced
  • 8 min read
  • 10 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, the Rust toolchain with Cargo, and a Cargo binary project

Your place in the module
By the end you can 3 objectives
  • State the three ownership rules and identify when a String is created and dropped.
  • Identify the current owner after an assignment, a by-value function call, or a return.
  • Use an E0382 diagnostic to locate a move and repair a later use of the moved binding.
Video coming soonThe three ownership rules and moves
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Dependencies, documentation, and compiler errors
  • Commit Cargo.lock for binaries but not for libraries.
  • Semantic versioning turns a requirement into a range; caret, tilde, and exact specifiers set different bounds, and 0.x versions are treated as unstable.
  • Doc comments /// and //! contain Markdown whose code blocks run as doctests under cargo test.
01

The three ownership rules

3 min read

In Dependencies, documentation, and compiler errors you read rustc's messages inside a Cargo project. This lesson answers the question behind the most famous one: why a value cannot be used after it has been moved.

A Linux monitoring program can read a task name from /proc/self/comm, which exposes the calling process's task name. The program may format that name in one function and send it to a logger in another. If the name lives in dynamically allocated memory, the program needs a specific point at which to release that memory. In C, a program that gets a buffer from malloc can release it with free, and passing the same already-freed pointer to free again has undefined behavior. In Rust, the compiler can determine which binding owns a String at each point in the program, including when the string changes hands. proc_pid_comm(5), free(3)

The examples use fixed text so that you can follow the ownership of one value without also handling file input. Rust's three ownership rules are:

  1. Every value has an owner.
  2. Each value has exactly one owner at a time.
  3. When the owner goes out of scope, Rust drops the value.

A can be the owner. In these examples, gives you the point where an owner normally leaves scope. Look at both the opening and closing braces when you trace a local variable.

rust
fn main() {
    {
        let name = String::from("sensor-agent");
        println!("{name}");
    }
    println!("Finished");
}

String::from("sensor-agent") creates an owned String with a heap buffer holding the text. The binding name becomes its owner when the let statement initializes it. Running println!("{name}") displays the text while leaving ownership with name. The inner block ends immediately after that line. Rust drops the string at the inner closing brace, before the outer println! runs.

One String in an inner blockCreateStringString::from allocatesthe buffername ownsStringPrint nameOwnershipstays withnameClose innerblockDropreleasesthe bufferCreateStringString::from allocatesthe buffername ownsStringPrint nameOwnershipstays withnameClose innerblockDropreleasesthe buffer
The String is created in the inner block and dropped at its closing brace

The first two rules answer who owns an existing value. The creation expression answers when that value comes into existence. In this example, the expression creates it when execution reaches the let statement. The third rule answers when cleanup happens. If you removed the first println!, the same closing brace would still mark the end of name's scope. The last use of the name and the point where Rust drops the string are separate events.

The compiler checks ownership at compile time. The cleanup itself happens during execution. Dropping a String releases the heap memory it owns through the allocator. Rust arranges that cleanup automatically, with no garbage collector and no manual free call in the Rust code. This applies while the program is running. Even if the program continues to use other strings later, this string's buffer has already been released to the allocator when its owning block ends.

The closing brace tells you where to look for cleanup, provided the binding still owns the value there. To confirm that condition, follow the value through any assignments and function calls that occur before the brace.

02

Assignment moves a String

3 min read

A occurs when you use an existing String to initialize another binding. Consider two blocks again, this time with the string created in the outer block.

rust
fn main() {
    let name = String::from("sensor-agent");

    {
        let label = name;
        println!("{label}");
    }

    println!("Finished");
}

Before let label = name, the owner is name. After the assignment, the owner is label. Both names belong to scopes that are still active at that point, but only label holds the string. The existing heap buffer belongs to the moved String throughout the transfer. The assignment creates a new binding and transfers the value to it without allocating a second buffer or duplicating the text.

At the end of the inner block, Rust drops the string owned by label. The outer scope continues to the Finished message. When that outer scope ends, there is no string left in name for Rust to drop. If you want to work out where a moved string is dropped, find the binding that owns it after the last move and find where that binding leaves scope.

Ownership after assignmentname ownsStringlet label =nameTransferthe sameStringlabel ownsStringClose innerblockDrop theString heldby labelname ownsStringlet label =nameTransferthe sameStringlabel ownsStringClose innerblockDrop theString heldby label
Ownership transfers to label, so the inner closing brace is where cleanup happens

A use of name after the assignment fails even when you put it inside the inner block, while label still owns the live string. The following example intentionally fails to compile:

rust
fn main() {
    let name = String::from("sensor-agent");
    let label = name;
    println!("{label}");
    println!("{name}");
}

Rust reports error E0382, a use of a moved value. In this example, the main diagnostic describes a borrow of a moved value because formatting with println! needs to read the string. Find the annotation value moved here on the assignment. Then find the annotation at the later use of name. The assignment is valid on its own. The compiler rejects the combination of that move and the subsequent attempt to use name. This is what cargo build prints for that program with rustc 1.100.1 (the wording of the help line can differ between compiler versions):

text
error[E0382]: borrow of moved value: `name`
 --> src/main.rs:5:16
  |
2 |     let name = String::from("sensor-agent");
  |         ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
3 |     let label = name;
  |                 ---- value moved here
4 |     println!("{label}");
5 |     println!("{name}");
  |                ^^^^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let label = name.clone();
  |                     ++++++++

The help line offers a clone. That fixes the error, but it allocates a second buffer. When you only need to read the text under one name, printing label needs no allocation at all.

This ordering matters when you decide how to fix the program. If the message belongs after the assignment, print using label. If you meant to print from name before transferring it, place that read before the assignment. Both changes use the same allocated string. A source name can still appear in its lexical scope after a move, so checking braces alone cannot tell you which name to use. Check which binding received the value most recently.

03

Ownership across function calls and returns

4 min read

The same transfer happens when you pass a String to a function whose parameter has type String. That parameter takes its argument by value. The caller starts as the owner, and the parameter becomes the owner as the function begins. To tell whether a call moves the string in these examples, inspect the parameter type and the argument expression. A named String supplied to a String parameter moves into it.

rust
fn log_name(label: String) {
    println!("{label}");
}

fn main() {
    let name = String::from("sensor-agent");
    log_name(name);
    println!("Finished");
}

name owns the string until the call to log_name. The parameter label owns it during the call. println! displays the text while leaving label as the owner. As log_name finishes, label goes out of scope and Rust drops the string. The caller then prints Finished. If the caller tried println!("{name}") after log_name(name), the compiler would point to the call as the move. The caller's binding lost ownership when the argument was passed, before the function reached its closing brace.

A return can transfer ownership in the other direction. A function that returns String supplies an owned value to its caller. It can return a string it created locally or return a string it previously received. Here it receives a string, displays it, and returns that same value:

rust
fn log_and_return(label: String) -> String {
    println!("{label}");
    label
}

fn main() {
    let name = String::from("sensor-agent");
    let logged = log_and_return(name);
    println!("{logged}");
}

The final expression label, written without a semicolon, supplies the function's return value. When that expression is evaluated, ownership moves out of label into the returned value. label ends its scope with no string left to drop. The caller initializes logged with the return value, and logged owns it until main ends. Ownership comes back to the caller through the return expression and the receiving binding. The original binding name still cannot be used to read the string.

Moves across a call and returnCallerlog_and_returnMove name into labelReturn String into loggedDrop at scope end1. Caller → log_and_returnMove name into label2. log_and_return → CallerReturn String into logged3. Caller → CallerDrop at scope end
The argument moves into the function, and the returned value moves to the caller's receiving binding

The same reasoning works if the function creates the value itself. Suppose its body is let label = String::from("sensor-agent"); followed by the final expression label, and its return type is String. The string is created inside that function. Returning it transfers ownership to the caller, where a binding initialized by the call can use it after the function's local scope has ended.

For a call that both accepts and returns a string, read the input and output independently. The String parameter tells you where the argument moves. The String return type tells you that the caller receives an owned string. The body tells you whether it returns the same value it received or creates a different one. In log_and_return, the final expression names the parameter, so you can trace one value from name to label to logged. There is one allocation for that string's text in the source example and one eventual drop of the string, even though three bindings own it at different times.

When you read a new example, start at the expression that creates the string and follow each transfer in execution order. At any line that uses the string, ask which binding owns it at that moment. At the end of each block or function, ask whether its local owner still holds the value or has already moved it away. The practice pack applies these questions to an inner block, a compiler error, and a function that returns ownership.

In Copy types and explicit clones, you will see why some types can still be used after assignment or a by-value call, and how to request a separate String when two bindings each need an owned value.

Key takeaways

  • Each value has exactly one owner at a time.
  • When the current owner goes out of scope, Rust drops the value automatically.
  • Moving a String transfers ownership of its existing heap buffer without duplicating its contents.
  • Rust checks ownership at compile time and runs cleanup without a garbage collector or a manual free call.
Reflect
  1. Explain to a colleague, in two sentences: state the three ownership rules and identify when a String is created and dropped.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close