Ownership is Rust's most distinctive feature and the foundation of its memory safety guarantees. Understanding ownership is the key to unlocking Rust's power. This chapter explains how ownership works, why it matters, and how to use it effectively.
In Rust, every value has exactly one owner. When the owner goes out of scope, the value is automatically freed. This simple rule eliminates entire categories of bugs: memory leaks, dangling pointers, and use-after-free errors.
Before diving into ownership, you need to understand where data lives in memory. This fundamental knowledge applies to all programming languages, but Rust makes you think about it explicitly.
Fixed size, LIFO, automatic cleanup
Dynamic size, requires manual or automatic management
The stack is a region of memory that operates like a stack of plates: last in, first out (LIFO). It's incredibly fast because:
fn main() {
let x = 42; // x is pushed onto the stack
let y = 3.14; // y is pushed onto the stack
let z = true; // z is pushed onto the stack
} // z, y, x are popped off the stack (in that order)
The heap is for data that can grow or shrink at runtime, or whose size isn't known at compile time:
fn main() {
let s = String::from("hello"); // String data is on the heap
// s variable (with pointer) is on the stack
// The actual "hello" bytes are on the heap
}
| Type | Location | Size |
|---|---|---|
Integers (i32, u64, etc.) |
Stack | Fixed |
Floats (f32, f64) |
Stack | Fixed |
Booleans (bool) |
Stack | Fixed |
Characters (char) |
Stack | Fixed (4 bytes) |
| Tuples (of fixed types) | Stack | Fixed |
String |
Stack (metadata) + Heap (data) | Dynamic |
Vec<T> |
Stack (metadata) + Heap (data) | Dynamic |
Rust's ownership system is governed by three fundamental rules. These rules are enforced at compile time, meaning violations are caught before your code ever runs.
let s = String::from("hello"); // s owns the String
// There is exactly one variable that owns this string data
let s1 = String::from("hello");
let s2 = s1; // Ownership MOVES from s1 to s2
// s1 is no longer valid - s2 is now the sole owner
{
let s = String::from("hello");
// s is valid here
} // s goes out of scope, "drop" is called
// Memory is automatically freed
These three rules eliminate:
When you assign a value to another variable, ownership can move. This is fundamental to understanding Rust.
Simple types that live entirely on the stack are copied:
let x = 5;
let y = x; // x is COPIED to y
println!("x = {}, y = {}", x, y); // Both are valid!
This works because copying an integer is cheap—it's just copying a few bytes on the stack.
For types that use heap memory, assignment moves ownership:
let s1 = String::from("hello");
let s2 = s1; // Ownership MOVES from s1 to s2
println!("{}", s2); // OK: s2 owns the data
// println!("{}", s1); // ERROR: s1 is no longer valid!
Copying heap data would require allocating new memory and copying all the bytes. For large data structures, this could be slow and wasteful. By default, Rust moves ownership instead, which is a constant-time operation.
When you actually need a deep copy of heap data, use the clone method:
let s1 = String::from("hello");
let s2 = s1.clone(); // Deep copy - both are independent
println!("s1 = {}, s2 = {}", s1, s2); // Both valid!
Cloning copies all heap data. For large data structures, this can be slow and use significant memory. Use clone() intentionally, not as a way to avoid learning ownership.
| Aspect | Copy | Clone |
|---|---|---|
| When it happens | Implicit, automatic | Explicit, must call .clone() |
| Performance | Cheap (stack only) | Potentially expensive (heap copy) |
| Types | Integers, floats, bool, char, tuples | String, Vec, custom types |
| Trait | Copy |
Clone |
Passing a value to a function follows the same rules as assignment:
fn main() {
let s = String::from("hello");
takes_ownership(s); // s is MOVED into the function
// println!("{}", s); // ERROR: s is no longer valid here
let x = 5;
makes_copy(x); // x is COPIED (integers implement Copy)
println!("{}", x); // OK: x is still valid
}
fn takes_ownership(some_string: String) {
println!("{}", some_string);
} // some_string goes out of scope, memory is freed
fn makes_copy(some_integer: i32) {
println!("{}", some_integer);
} // some_integer goes out of scope, nothing special happens
Functions can return ownership:
fn main() {
let s1 = gives_ownership(); // Ownership moves to s1
let s2 = String::from("hello");
let s3 = takes_and_gives_back(s2); // s2 moves in, result moves to s3
// s2 is invalid here, s1 and s3 are valid
}
fn gives_ownership() -> String {
let s = String::from("yours");
s // Ownership moves to the caller
}
fn takes_and_gives_back(a_string: String) -> String {
a_string // Ownership moves back to the caller
}
When a value goes out of scope, Rust calls the drop function. This is where cleanup happens:
struct CustomSmartPointer {
data: String,
}
impl Drop for CustomSmartPointer {
fn drop(&mut self) {
println!("Dropping CustomSmartPointer with data: {}", self.data);
}
}
fn main() {
let c = CustomSmartPointer {
data: String::from("my stuff"),
};
println!("CustomSmartPointer created.");
} // c goes out of scope here, "Dropping..." is printed
Rust uses RAII (from C++) - resources are acquired when an object is created and released when it's destroyed. This guarantees cleanup even if errors occur. Files are closed, locks are released, memory is freed - all automatically.
fn process_data(data: String) -> String {
// Process the data
data.to_uppercase()
}
fn main() {
let input = String::from("hello");
let output = process_data(input); // input moved, output received
println!("{}", output);
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len();
(s, length) // Return both the string and its length
}
fn main() {
let s = String::from("hello");
let (s, len) = calculate_length(s);
println!("'{}' has length {}", s, len);
}
Having to return values just to give them back is tedious. In the next chapter, you'll learn about borrowing, which lets you use values without taking ownership.
.clone() for explicit deep copies (be aware of performance cost)String to another variable? Why is this different from assigning an i32?.clone() on a String? What are the performance implications?Having to transfer ownership every time you want to use a value is cumbersome. The next chapter introduces borrowing—a way to use values without taking ownership: