Understanding Rust's Ownership Model
Grasp the core rules of ownership, move semantics, and how they prevent common memory errors like double-free.
Understanding Rust's Ownership Model is a free Learn Rust Coding lesson on CoddyKit — lesson 1 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is Rust Ownership?
Rust's ownership system is a set of rules that manage how your program uses memory. It's a core concept that helps Rust achieve memory safety without a garbage collector.
- No dangling pointers.
- No double-free errors.
- No data races in concurrent code.
It checks these rules at compile time!
Stack vs. Heap Memory
Programs use two main memory areas: the stack and the heap.
- Stack: Faster, fixed-size data (like integers, booleans, known-size types). Data is pushed and popped in order.
- Heap: Slower, variable-size data (like
String,Vec). Data is requested and returned by the allocator.
Ownership primarily manages data on the heap, ensuring its safe use and cleanup.
Rule 1: Every Value Has an Owner
The first rule of ownership is simple: each value in Rust has a variable that's called its owner.
Think of it like a label on a box. The variable s below is the owner of the text "hello".
fn main() {
let s = String::from("hello"); // s owns "hello"
println!("{}", s);
}Rule 2: Only One Owner at a Time
The second rule states: at any given time, there can only be one owner for a value. This is crucial for preventing memory issues.
When you assign a complex value (like a String, which lives on the heap) from one variable to another, ownership is moved, not copied.
Ownership Transfer in Action
See what happens when s1's value is assigned to s2. Try running the code.
fn main() {
let s1 = String::from("Hello, CoddyKit!");
let s2 = s1; // Ownership of the String data moves from s1 to s2
// println!("{}", s1); // This line would cause a compile-time error!
println!("{}", s2);
}Understanding "Move" Semantics
After let s2 = s1;, s1 is no longer considered valid. Rust prevents you from using s1 again.
- This is called a move. The pointer, length, and capacity on the stack are copied, but the heap data itself is not.
- If
s1were still valid, boths1ands2would try to free the same memory when they go out of scope (a double-free error).
Rust's ownership system prevents this at compile time!
Ownership and Function Calls
Passing a value to a function works similarly to assigning it to another variable: ownership is moved into the function.
When the function finishes, the value's owner (the function parameter) goes out of scope, and the value is dropped.
Function Ownership Demo
Observe how the String value is moved into takes_ownership and then gives_ownership returns a new String.
fn takes_ownership(some_string: String) {
println!("Inside takes_ownership: {}", some_string);
} // some_string goes out of scope and `drop` is called.
fn gives_ownership() -> String {
let some_string = String::from("returned string");
some_string // Ownership is moved out of the function
}
fn main() {
let s1 = String::from("hello");
takes_ownership(s1); // s1's value moves into takes_ownership
// println!("{}", s1); // Error: s1 is no longer valid here!
let s2 = gives_ownership(); // s2 gets ownership of the returned String
println!("After gives_ownership: {}", s2);
}Rule 3: Scope & Dropping
The final rule: when the owner goes out of scope, the value will be dropped.
- A scope is the range within a program for which an item is valid, usually defined by
{}curly brackets. - When a variable goes out of scope, Rust automatically calls a special function called
drop.
This ensures memory is cleaned up automatically, safely, and without a garbage collector.
Preventing Memory Errors
The ownership rules work together to guarantee memory safety:
- One owner: Prevents multiple parts of your code from trying to free the same memory.
- Drop on scope end: Ensures memory is freed exactly once, and at the correct time.
This eliminates common bugs like double-free errors and use-after-free errors at compile time, giving you peace of mind!
Ownership Check
Consider the following Rust code. What will happen when you try to compile and run it?
fn main() {
let message = String::from("Rust is fun!");
let greeting = message;
println!("{}", message);
}Recap: Ownership Basics
Great job! You've learned the fundamental rules of Rust's ownership system:
- Every value has an owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped.
This system prevents common memory errors without a garbage collector. Next, we'll explore borrowing to share data without transferring ownership.
Frequently asked questions
Is the “Understanding Rust's Ownership Model” lesson free?
Yes — the full text of “Understanding Rust's Ownership Model” is free to read here on the web, and the Learn Rust Coding course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Understanding Rust's Ownership Model”?
Grasp the core rules of ownership, move semantics, and how they prevent common memory errors like double-free. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Understanding Rust's Ownership Model” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Understanding Rust's Ownership Model
- References and Borrowing Explained
- Lifetimes for Safe References