Module 2 · Ownership & memory
2.2Ownership and move semantics
Why assigning a Vec or String in Rust moves it instead of sharing it, what the compiler checks, and how that replaces a garbage collector.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Who frees memory | The garbage collector, some time after nothing references the object | The garbage collector, some time after nothing references the object | The owner, at the moment it goes out of scope |
b = a with a list | Copies the reference; both names share one array | Copies the reference; both names share one List<T> | Moves the value; a can't be used anymore |
| Passing a list to a function | The function shares the caller's array | The function shares the caller's list | The function takes ownership, unless you pass a clone or a borrow |
| Using a value after giving it away | Always allowed | Always allowed | Compile error E0382 |
| Numbers and booleans | Copied | Copied (value types) | Copied: they implement Copy |
TypeScriptC# never asks who owns an object. Any number of variables can point at the same arraylist, and the garbage collector frees it some time after the last one lets go. Rust has no garbage collector. Instead, every value has exactly one owner, and the compiler tracks that owner through your whole program.
The three rules
- Every value has an owner: the variable that holds it.
- There is one owner at a time.
- When the owner goes out of scope, the value is dropped: its memory is freed right there.
{
let name = String::from("Ada"); // `name` owns a heap buffer
println!("{name}");
} // `name` goes out of scope: Rust frees the buffer hereThere’s no free, no delete and no collector pause. The compiler inserts the cleanup at the closing brace, because it knows name is the only owner.
Assignment moves the value
Here’s the same short program in TypeScriptC# and in Rust. The TypeScriptC# version ends with one arraylist and two names pointing at it.
const team = ["Ada", "Grace"];
const newTeam = team;
newTeam.push("Linus");
console.log(team.length);var team = new List<string> { "Ada", "Grace" };
var newTeam = team;
newTeam.Add("Linus");
Console.WriteLine(team.Count);let team = vec![String::from("Ada"), String::from("Grace")];
let mut new_team = team; // ownership moves to `new_team`
new_team.push(String::from("Linus"));
println!("{}", new_team.len());Output
3
In TypeScript, newTeam.push changes the array team points at too, so team.length is 3.In C#, newTeam.Add changes the list team points at too, so team.Count is 3. In Rust, let mut new_team = team; moves the vector: new_team is now the only owner, and team can’t be used anymore. That’s why the Rust version prints new_team.len().
Mental model shift= means 'move', not 'share'
In TypeScriptC#, assigning an object (an instance of a class; structs are copied) copies a reference, so two names share one object. In Rust, assigning a value whose type isn’t Copy (anything that owns heap memory, and your own structs unless you opt in) hands ownership to the new name. Nothing is shared, so there’s never a question of who frees it.
What happens if you use it anyway
Try to read team after the move. TypeScriptC# prints 2 2. Rust refuses to compile:
const team = ["Ada", "Grace"];
const newTeam = team;
console.log(team.length, newTeam.length);var team = new List<string> { "Ada", "Grace" };
var newTeam = team;
Console.WriteLine($"{team.Count} {newTeam.Count}");let team = vec![String::from("Ada"), String::from("Grace")];
let new_team = team;
println!("{} {}", team.len(), new_team.len());Rust doesn't compile this: error E0382
error[E0382]: borrow of moved value: `team`
--> team.rs:3:19
|
1 | let team = vec![String::from("Ada"), String::from("Grace")];
| ---- move occurs because `team` has type `Vec<String>`, which does not implement the `Copy` trait
2 | let new_team = team;
| ---- value moved here
3 | println!("{} {}", team.len(), new_team.len());
| ^^^^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
2 | let new_team = team.clone();
| ++++++++The message points at all three steps: where team got its value, where it moved, and where you tried to use it afterwards.
Line by line, team owns the vector only until the move:
| Line | Code | teamowner | teammoved out | new_teamowner | What happens |
|---|---|---|---|---|---|
| 1 | let team = vec![String::from("Ada"), String::from("Grace")]; | ownsteam starts | team owns the vector | ||
| 2 | let new_team = team; | movedteam starts | ownsnew_team starts | Ownership moves to new_team; team can't be used from here on | |
| 3 | println!("{} {}", team.len(), new_team.len()); | team ends | new_team ends | errorError E0382: team was moved on line 2 |
Three lines of code. On line 1, team owns the vector. On line 2, let new_team = team moves ownership: new_team owns the vector from line 2 to the end of the scope, and team is marked moved from line 2 on. Line 3 reads team.len(), so the compiler rejects it with error E0382, borrow of moved value.
Caught at compile timeUse after move
In C or C++, two owners of one buffer can both free it (a double free), or one can read it after the other freed it (a use after free). Both are classic security bugs. TypeScriptC# avoids them by never freeing while anything still points at the object. Rust avoids them by allowing only one owner, and it checks this before the program runs, at no runtime cost.
Moving into a function
Passing a value to a function is an assignment too: the parameter becomes the owner. When the function returns, its parameters go out of scope, so the value is dropped, unless the function returned it or stored it somewhere.
function printTeam(team: string[]): void {
console.log(team.join(", "));
}
const team = ["Ada", "Grace"];
printTeam(team);
console.log(team.length);var team = new List<string> { "Ada", "Grace" };
PrintTeam(team);
Console.WriteLine(team.Count);
static void PrintTeam(List<string> team) => Console.WriteLine(string.Join(", ", team));fn print_team(team: Vec<String>) {
println!("{}", team.join(", "));
} // `team` is dropped here: this function owned it
fn main() {
let team = vec![String::from("Ada"), String::from("Grace")];
print_team(team.clone()); // give the function its own copy
println!("{}", team.len());
}Output
Ada, Grace 2
Without .clone(), the call would move team into print_team, and the last line would fail with the same E0382 as before. .clone() makes a full, independent copy for the function to own and drop.
Idiomatic RustLend, don't clone
Cloning works, but it copies the vector and every string in it. A function that only reads its argument should borrow it instead: fn print_team(team: &[String]), called as print_team(&team). Borrowing is the subject of Module 3.
Which one should I use?
When you hand a value to another variable or a function, you have four options. In TypeScriptC# you rarely choose, because objectsclass instances are always shared. In Rust you choose every time, and the compiler holds you to it.
| What | When | Why | How |
|---|---|---|---|
| Move | You’re done with the value, or the receiver should own it from now on (store it, return it, consume it). | Cheap: only the value’s inline bytes are copied (for a String or Vec, the pointer, length and capacity), never the heap data. The compiler stops you using the old name by accident. | Assign or pass it as is: let b = a;, keep(a). |
Borrow (&) | The receiver only needs to look at the value for a while. | No copy, and you keep ownership. This is the most common choice. | Pass &a to a function that takes &T. Module 3 covers it in depth. |
| Clone | You really need two independent values that can change separately. | Each owner frees its own copy, so nothing is shared. | let b = a.clone();. It copies all the heap data, so it costs time and memory. |
| Copy | The type implements Copy: integers, f64, bool, char, and tuples and arrays of them. Your own types can opt in (next lesson). | Copying a few bytes is as cheap as moving them. | Nothing to decide: let b = a; copies and both stay usable. |
Rule of thumb: borrow if the receiver only reads, move if it should keep the value, and clone only when you truly need a second copy. If you find yourself adding .clone() just to make an error go away, a borrow is usually the better fix.
Under the hood
A String is three numbers on the stack (a pointer to its heap buffer, a length and a capacity) plus the text itself on the heap. A Vec has the same shape. Moving one copies only those three numbers:
let name = String::from("Ada");
let new_name = name;
println!("{new_name}");After the move, the old variable’s bits are still on the stack, but the compiler treats name as uninitialized. Because only new_name counts as the owner, the buffer is freed exactly once, when new_name goes out of scope. A move costs about the same as copying a reference in TypeScriptC#: no heap data is copied.
Common pitfalls
Common pitfallA for loop moves the collection
for name in team takes ownership of team and hands you each string by value. After the loop, team is gone:
let team = vec![String::from("Ada"), String::from("Grace")];
for name in team {
println!("{name}");
}
println!("{}", team.len());Rust doesn't compile this: error E0382
error[E0382]: borrow of moved value: `team`
--> main.rs:5:16
|
1 | let team = vec![String::from("Ada"), String::from("Grace")];
| ---- move occurs because `team` has type `Vec<String>`, which does not implement the `Copy` trait
2 | for name in team {
| ---- `team` moved due to this implicit call to `.into_iter()`
...
5 | println!("{}", team.len());
| ^^^^ value borrowed here after move
|
note: `into_iter` takes ownership of the receiver `self`, which moves `team`
help: consider iterating over a slice of the `Vec<String>`'s content to avoid moving into the `for` loop
|
2 | for name in &team {
| +Loop over a borrow instead, with for name in &team, and team is still yours afterwards:
let team = vec![String::from("Ada"), String::from("Grace")];
for name in &team {
println!("{name}");
}
println!("{}", team.len());Common pitfallNot every assignment is a move
Numbers, bool, char and other types that implement Copy are simply copied, as in TypeScriptC#. Both variables stay usable:
let count = 3;
let other = count; // i32 is Copy: both stay usable
println!("{count} {other}");Which types copy and which move is the next lesson: Copy vs. Clone.
Try it yourself
Exercise: port this to Rust
Port this program to Rust. Write a shout function that takes a String and returns a new one, and keep printing message after the call.
function shout(message: string): string {
return message.toUpperCase() + "!";
}
const message = "hello";
const loud = shout(message);
console.log(`${message} -> ${loud}`);var message = "hello";
var loud = Shout(message);
Console.WriteLine($"{message} -> {loud}");
static string Shout(string message) => message.ToUpper() + "!";Expected output
hello -> HELLO!
Show a hint
If shout takes a String, calling it moves message into the function. Give it a copy with .clone() so you can still print message afterwards.
Show a solution
fn shout(message: String) -> String {
message.to_uppercase() + "!"
}
fn main() {
let message = String::from("hello");
let loud = shout(message.clone());
println!("{message} -> {loud}");
}shout owns its argument, so main passes a clone and keeps message. Once you've learned borrowing, you'd write shout(message: &str) and call shout(&message), with no copy at all.
Saved in this browser only.