Ownership
Rust's central idea — every value has one owner, ownership moves on assignment, values are dropped when their owner goes out of scope — plus Copy vs move types, Clone, stack vs heap, and how this replaces garbage collection.
Most languages manage heap memory either manually (C: malloc/free, with use-after-free and leak bugs) or with a garbage collector (Java, Go, Python: safe, but with runtime overhead and pauses). Rust takes a third path: a set of ownership rules checked at compile time. If the program compiles, memory is freed exactly once, at a predictable point, and never used after being freed — with zero runtime cost.
The three rules
- Each value has an owner (a variable).
- There can be only one owner at a time.
- When the owner goes out of scope, the value is dropped (its memory and resources are freed).
{
let s = String::from("hello"); // s owns a heap buffer
// use s
} // scope ends: drop(s) runs automatically, freeing the bufferThis is RAII (resource acquisition is initialisation), as in C++: files, sockets, locks and memory are all released by Drop when their owner goes away.
Moves
Assigning a heap-owning value to another variable moves ownership; the original becomes unusable:
let s1 = String::from("hello");
let s2 = s1; // ownership moves to s2
println!("{s1}"); // ✗ error[E0382]: borrow of moved value: `s1`Why not copy the heap data? That would be expensive and implicit. Why not let both point to it? Then both would try to free it at the end of scope — a double free. Moving is cheap (copy three words: pointer, length, capacity) and keeps exactly one owner.
Moves also happen when passing to functions and returning from them:
fn take(s: String) { // s comes into scope, owning the value
println!("{s}");
} // s dropped here
fn give() -> String {
String::from("yours") // ownership moves out to the caller
}
let a = String::from("hi");
take(a); // a moved into take
// println!("{a}"); // ✗ a is no longer valid
let b = give(); // b owns the returned StringPassing ownership back and forth is clumsy — that's what borrowing solves (Borrowing & lifetimes).
Copy types
Simple values that live entirely on the stack — integers, floats, bool, char, and tuples/arrays of them — implement the Copy trait. Assignment duplicates them, and the original stays valid:
let x = 5;
let y = x; // copy
println!("{x} {y}"); // ✓ both validA type can be Copy only if all its parts are Copy and it has no Drop logic — so String, Vec and Box are never Copy.
Clone: explicit deep copies
When you really want two independent heap copies, say so:
let s1 = String::from("hello");
let s2 = s1.clone(); // allocates and copies the bytes
println!("{s1} {s2}"); // ✓Seeing .clone() in code is a visible signal of a potentially expensive operation — unlike languages where copies happen implicitly.
Stack and heap
| Stack | Heap | |
|---|---|---|
| Holds | Fixed-size values: integers, structs of known size, pointers | Dynamically sized data: String contents, Vec elements, Box<T> |
| Allocation | Moving a stack pointer — extremely cheap | Allocator call — slower |
| Freed | Automatically when the function returns | When the owner is dropped (Rust) |
A String variable is a stack struct (pointer, length, capacity) that owns a heap buffer. Ownership is how Rust knows when to free the heap part. See Memory: stack & heap.
Drop order and the Drop trait
struct Connection { name: String }
impl Drop for Connection {
fn drop(&mut self) {
println!("closing {}", self.name); // cleanup logic runs automatically
}
}
fn main() {
let _a = Connection { name: "a".into() };
let _b = Connection { name: "b".into() };
// prints "closing b" then "closing a" — dropped in reverse declaration order
drop(_a); // or drop early, explicitly (std::mem::drop takes ownership)
}Ownership and collections
let names = vec![String::from("ada"), String::from("alan")];
for name in names { // into_iter: takes ownership; each name is moved out
println!("{name}");
}
// names is gone here
let names = vec![String::from("ada")];
for name in &names { // iterate by reference: borrow, don't take
println!("{name}");
}
println!("{}", names.len()); // ✓ still valid
let first = names[0]; // ✗ cannot move out of index — would leave a hole in the Vec
let first = &names[0]; // ✓ borrow
let first = names[0].clone(); // ✓ copyWhy this matters
| Bug class | How ownership prevents it |
|---|---|
| Use after free | Using a moved-from or dropped value is a compile error |
| Double free | Only one owner ever drops a value |
| Memory leaks (mostly) | Values are dropped deterministically at scope end (leaks are possible but rare and explicit: Rc cycles, mem::forget) |
| Resource leaks | Files, sockets, locks released by Drop |
| Data races | Combined with borrowing rules and Send/Sync (Fearless concurrency) |
- Every value has exactly one owner; it's dropped when the owner goes out of scope (RAII).
- Assigning or passing a heap-owning value moves it; the old binding becomes invalid.
- Copy types (integers, bool, char…) are duplicated instead of moved.
- clone() makes explicit deep copies.
- Ownership eliminates use-after-free and double-free at compile time with no GC.
QHow does Rust manage memory without a garbage collector?medium
Through ownership checked at compile time: every value has a single owner, ownership moves on assignment or when passed by value, and the value is dropped deterministically when its owner goes out of scope. Borrowing lets code use values temporarily without taking ownership, and the borrow checker ensures references never outlive the data or alias mutable data. The compiler inserts the frees, so there's no runtime collector.