Rust Ownership
🦀 Rust Ownership
It is the reason Rust is memory-safe, fast, and does not need a garbage collector.
If you understand Ownership, you understand the core of Rust.
🧠 What Is Ownership?
Ownership is a set of rules that the Rust compiler uses to manage memory.
It decides:
-
Who owns a value
-
When memory should be freed
-
How to prevent memory bugs (null pointers, data races, use-after-free)
All checks happen at compile time, not runtime.
🔑 The 3 Ownership Rules
✅ Rule 1: Each value has one owner
Here:
-
"Rust"is stored on the heap -
sis the owner of that memory
✅ Rule 2: Only one owner at a time
Now:
-
Ownership moves from
s1tos2 -
s1becomes invalid
This prevents double free errors.
✅ Rule 3: When the owner goes out of scope, memory is freed
✔ No memory leaks
✔ No manual free()
✔ No garbage collector
🔹 Stack vs Heap (Why Ownership Exists)
| Stack | Heap |
|---|---|
| Fixed size | Dynamic size |
| Fast | Slower than stack |
| Simple values | Complex values |
Ownership mainly applies to heap data.
🔹 Move vs Copy
▶️ Copy Types (Ownership Not Moved)
Because i32 is a Copy type.
Common Copy types:
-
Integers (
i32,u64, etc.) -
Floating-point numbers
-
bool -
char -
Tuples (if all elements are Copy)
▶️ Move Types (String, Vec, etc.)
Heap data cannot be copied automatically, so ownership is moved.
🔹 Ownership and Functions
▶️ Passing Ownership to a Function
Ownership moves into the function.
▶️ Returning Ownership from a Function
Ownership is transferred back.
🔹 Borrowing (Ownership Without Transfer)
To avoid moving ownership, Rust uses borrowing.
✔ Ownership stays with name
✔ Function only borrows the value
🔹 Mutable Borrowing Rules (Preview)
Rules:
-
You can have multiple immutable references, OR
-
One mutable reference
-
Not both at the same time
This prevents data races.
❌ Common Beginner Mistakes
-
Treating
Stringlike an integer -
Forgetting ownership moves
-
Trying multiple mutable references
-
Ignoring compiler error messages
👉 Rust compiler errors are very helpful, not enemies.
🧠 Ownership Summary
| Concept | Meaning |
|---|---|
| Owner | Variable that controls memory |
| Move | Ownership transfer |
| Copy | Value duplicated |
| Scope end | Memory freed |
| Borrow | Temporary access without ownership |
