Welcome back! In our first lesson, we covered the fundamental syntax of Rust, including variables, data types, functions, and control flow. We saw that Rust's default to immutability is a deliberate design choice that encourages safer code. Today, we'll explore the logical conclusion of that design philosophy: Rust's ownership system.
This lesson addresses what is arguably Rust's most unique and powerful feature. For anyone with a C or C++ background, you know that manual memory management is both a source of great power and a frequent cause of bugs like dangling pointers, double frees, and memory leaks. Python, on the other hand, handles this for you with a garbage collector, trading some performance and control for convenience. Rust offers a third path.
By the end of this lesson, you will be able to explain Rust's ownership model, including its rules for transferring ownership (move semantics) and the exception for simple types (the Copy trait). This is the key to understanding how Rust achieves memory safety at compile time, without needing a garbage collector.
Why Ownership? The Problem of Memory Management
Every program must manage its memory. Rust's approach is a primary reason for its existence, aiming to provide the performance of C++ with stronger safety guarantees. To understand the trade-offs, it's helpful to see where Rust's ownership model fits in.
Understanding Ownership in Rust
Let's start with the video "Understanding Ownership in Rust" from the Let's Get Rusty channel.
This first segment provides an excellent high-level overview. It compares Rust's ownership model with garbage collection (like in Python) and manual memory management (like in C/C++). Watch from the beginning to the end of the comparison. This will frame the "why" behind what we're about to learn.
As the video explains, Rust's goal is to provide the control and performance of manual management while eliminating entire classes of memory errors at compile time. The mechanism that enables this is ownership.
To understand ownership, we first need to quickly revisit how memory is organized, a concept you'll be familiar with from C and C++.
What is Ownership? - The Rust Programming Language
This chapter from the official Rust book is the definitive guide to ownership. We'll be using it throughout the lesson.
First, read the section on the stack and heap. This recap is essential because ownership is primarily about managing heap-allocated data.
The key distinction is that the stack is for data with a known, fixed size, while the heap is for data with an unknown or dynamic size. Pushing to the stack is fast and simple. Allocating on the heap is more complex, as the system must find a free block of memory and return a pointer. Ownership is Rust's system for managing this heap memory automatically and safely.
The Three Rules of Ownership
The entire ownership system is built on three simple rules that are checked by the compiler.
What is Ownership? - The Rust Programming Language
Now, let's look at the core principles.
Read the short section titled "Ownership Rules". Memorize these three rules, as everything else follows from them.
To reiterate, the rules are:
- Each value in Rust has an owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped.
The third rule is the most critical for memory management. When a value is "dropped," Rust automatically calls special code to deallocate its resources. For a heap-allocated String, this means freeing the memory on the heap. This deterministic cleanup at the end of a scope is a pattern known as RAII (Resource Acquisition Is Initialization) in C++, where destructors are called when an object goes out of scope. In Rust, this is built into the language for all types.
Move Semantics: Transferring Ownership
Let's see these rules in action. With simple, stack-only data like integers, things behave as you'd expect:
let x = 5;
let y = x; // A copy of the value 5 is made. Both x and y are valid.
However, it's different for heap-allocated data. In the last lesson, we saw the String type, which manages a growable string on the heap. Consider this code:
let s1 = String::from("hello");
let s2 = s1;
In C++, if s1 were a std::string, this would typically create a deep copy of the string data. In Python, it would create another reference to the same string object. Rust does something different.
To prevent a "double free" error (where both s1 and s2 would try to free the same memory when they go out of scope), Rust considers s1 to be no longer valid after the assignment. Ownership of the heap data has been moved from s1 to s2.
If you try to use s1 after the move, the compiler will stop you:
let s1 = String::from("hello");
let s2 = s1;
// println!("The value of s1 is: {}", s1); // This line will not compile!
This is the core of move semantics. For a detailed explanation with helpful diagrams, let's turn back to the Rust book.
What is Ownership? - The Rust Programming Language
This is the most crucial part of the lesson. It explains how and why Rust moves ownership.
Start by reading about the String type to understand why it's a good example. Then, carefully study the section "Variables and Data Interacting with Move". Pay close attention to Figures 4-1, 4-2, and 4-4, which illustrate what's happening in memory.
This behavior is a fundamental difference from C++. Whereas C++ defaults to making expensive copies unless you explicitly use move semantics (with std::move), Rust defaults to inexpensive moves for heap-allocated types.
To see a direct comparison, the following video segment is highly relevant to your C++ background.
Rust for C++ developers - What you need to know to get rolling with crates - Pavel Yosifovich
This video, "Rust for C++ developers," directly contrasts the default behaviors of the two languages.
Watch the segment from here, where the presenter compares assignment for std::vector in C++ with Vec (Rust's vector type) in Rust. He demonstrates the move default, the resulting compile error, and the use of .clone().
As the video shows, if you do want to perform a deep copy of heap data (like the default behavior of std::string or std::vector in C++), you must be explicit and call the clone() method.
let s1 = String::from("hello");
let s2 = s1.clone(); // s2 is now a deep copy of s1.
println!("s1 = {}, s2 = {}", s1, s2); // This works fine!
A call to .clone() is a clear signal that a potentially expensive operation is happening.
Copy Semantics: The Copy Trait
So, why did let y = x; work for an integer but not for a String?
The reason is that types like integers, which are stored entirely on the stack and have a known, fixed size, implement a special trait called Copy. A trait in Rust is a way to define shared behavior, similar to an interface in other languages.
If a type implements Copy, variables of that type are not moved on assignment; they are trivially copied. Since the data is just a few bytes on the stack, this is always a cheap operation.
What is Ownership? - The Rust Programming Language
Let's read the official explanation of this exception to the move rule.
Read the section on stack-only data. It lists the types that implement Copy by default. Notice the rule: a type can implement Copy only if none of its parts require special cleanup (i.e., implement the Drop trait). This is why String cannot be Copy.
The general rule is:
- Types that manage resources on the heap (like
StringorVec) are moved. - Simple scalar types stored entirely on the stack (like
i32,f64,bool,char) are copied.
This diagram provides a great visual summary of the two behaviors. For now, focus on the top two sections, "move" and "copy".

Ownership and Functions
The rules of ownership also apply when passing values to functions and returning values from them.
- Passing a value to a function will either move or copy it, just like assignment.
- Returning a value from a function also transfers ownership.
fn main() {
let s = String::from("hello"); // s comes into scope
takes_ownership(s); // s's value is moved into the function...
// ...and is no longer valid here.
let x = 5; // x comes into scope
makes_copy(x); // x is copied into the function,
// but i32 is Copy, so x is still valid here.
} // Here, x goes out of scope, then s. But because s's value was moved, nothing
// special happens.
fn takes_ownership(some_string: String) { // some_string comes into scope
println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) { // some_integer comes into scope
println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
This can feel a bit restrictive. What if we want a function to use a value without taking ownership of it? We could pass ownership in and then have the function return it back to us, but that's clumsy.
This exact problem is what leads us to the next core concept in Rust.
Conclusion
In this lesson, we have explored the heart of Rust's safety guarantees: the ownership system. You've learned how it differs from both manual memory management and garbage collection.
Here are the key takeaways:
- Rust enforces three ownership rules at compile time to manage memory safely: one owner per value, ownership is exclusive, and values are dropped when the owner goes out of scope.
- For heap-allocated data (like
String), assignment results in a move. Ownership is transferred, and the original variable becomes invalid. - For simple stack-only data that implements the
Copytrait (likei32), assignment results in a copy. Both variables remain valid. - If you need a deep copy of heap data, you must explicitly call the
.clone()method.
You now understand the fundamental rules governing how Rust programs manage their data. The rigidity of moving ownership into functions might seem inconvenient, but Rust provides an elegant solution. In our next lesson, we will introduce references and borrowing, which allow you to lend access to data without giving up ownership. This is the final piece of the ownership puzzle.