Rust Ownership
Ownership is the feature that makes Rust different from almost every other language. It is how Rust manages memory without a garbage collector and without manual free calls — and it is checked entirely at compile time, so it costs nothing while your program runs.
The three rules
- Every value in Rust has a single owner (a variable).
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped (its memory is freed).
That's it. Everything else in this chapter follows from these rules.
Stack and heap, briefly
Simple values with a fixed size — integers, floats, bool, char — live on the stack and are cheap to copy. Values that can grow, such as String and Vec, keep their contents on the heap; the variable itself holds a small pointer, length and capacity. Ownership is mostly about who is responsible for freeing that heap memory.
Moving a value
When you assign a String to another variable, Rust does not copy the heap text. It moves ownership: the new variable becomes the owner and the old one can no longer be used.
fn main() {
let a = String::from("lunchbox");
let b = a; // ownership moves from a to b
println!("b owns: {}", b);
// a can no longer be used here
}b owns: lunchbox
If you try to use a after the move, the program will not compile:
fn main() {
let a = String::from("lunchbox");
let b = a;
println!("{}", a);
}error[E0382]: borrow of moved value: `a`
--> src/main.rs:4:20
|
2 | let a = String::from("lunchbox");
| - move occurs because `a` has type `String`, which does not implement the `Copy` trait
3 | let b = a;
| - value moved here
4 | println!("{}", a);
| ^ value borrowed here after moveWhy so strict? If both a and b owned the same heap text, both would try to free it at the end of main — a "double free" bug. By allowing only one owner, Rust makes that impossible.
Copy types
Small stack-only types implement the Copy trait. Assigning them makes a cheap bit-for-bit copy, and both variables stay valid.
fn main() {
let x = 10;
let y = x; // i32 is Copy: x is copied, not moved
let flag = true;
let other = flag;
println!("x = {}, y = {}", x, y);
println!("flag = {}, other = {}", flag, other);
}x = 10, y = 10
flag = true, other = true
Copied on assignment (Copy) |
Moved on assignment |
|---|---|
i32, u8, f64 and all other numbers |
String |
bool, char |
Vec<T> |
tuples/arrays made only of Copy types |
Box<T>, HashMap and most structs |
Cloning: an explicit deep copy
If you really want two independent copies of heap data, ask for one with .clone(). Cloning is visible in the code on purpose, because it can be expensive.
fn main() {
let original = String::from("recipe");
let mut copy = original.clone();
copy.push_str(" (edited)");
println!("original: {}", original);
println!("copy : {}", copy);
}original: recipe
copy : recipe (edited)
Ownership and functions
Passing a value to a function works exactly like assignment: a String is moved into the function's parameter, and dropped when the function ends — unless the function gives it back by returning it.
fn take(text: String) {
println!("take() now owns: {}", text);
} // text is dropped here
fn take_and_give_back(mut text: String) -> String {
text.push('!');
text // ownership moves back to the caller
}
fn make_copy(n: i32) {
println!("make_copy() got: {}", n);
}
fn main() {
let s1 = String::from("hello");
take(s1);
// s1 is gone now
let s2 = String::from("hey");
let s3 = take_and_give_back(s2);
println!("Got back: {}", s3);
let n = 5;
make_copy(n);
println!("n is still usable: {}", n);
}take() now owns: hello
Got back: hey!
make_copy() got: 5
n is still usable: 5
Moving values in and out of every function would get tiresome quickly. Luckily there is a better way: borrowing, which lets a function use a value without taking ownership. That is the topic of the next chapter.
Tip: When the compiler says "value used here after move", ask yourself: should the function borrow the value (
&T) instead of taking it, or do I really need a.clone()?
Go further: Rust: Ownership, unsafe, FFI and Migration maps the borrow checker's rules to the C bug classes it rules out.
Test yourself
After let a = String::from("x"); let b = a;, which variable can be used?
- Both
aandb - Only
a - Only
b - Neither
Why can you still use x after let x = 5; let y = x;?
- Integers implement
Copy, soxis copied - Integers are always borrowed
- Rust ignores ownership for
let yis a reference tox
When is the memory of a String freed?
- When the garbage collector runs
- When you call
free() - When its owner goes out of scope
- Never