🧠 Ownership in Rust
Ownership is what makes Rust memory-safe without a garbage collector. It’s unique, powerful, and once you “get it,” you’ll start seeing the magic.
🪄 What Is Ownership?
Think of variables in Rust as owners of data. When a variable owns a value, it’s responsible for cleaning it up when it’s no longer used.
Here, s
owns the string "hello"
. When s
goes out of scope at the end of main()
, Rust automatically cleans up the memory.
👉 No need to call free()
or use a garbage collector!
🔁 Move: Ownership Transfer
When you assign a variable or pass it to a function, ownership moves:
s1
gives up ownership. Rust does this to prevent double-free errors. Only one variable owns the data at a time.
⚠️ This only happens for heap-allocated types like String
. For simple types like integers, Rust copies instead of moves.
📦 Functions and Ownership
Passing ownership into functions follows the same rules:
If you want to return ownership, you can!
🧬 Cloning (Explicit Copying)
If you want to make a real copy of heap data, use .clone()
:
Cloning can be expensive, so Rust makes it explicit — only clone when you really need to.
🧠 Summary
- Every value in Rust has an owner
- Ownership moves when variables are assigned or passed into functions
- Only one owner at a time — when the owner goes out of scope, the value is dropped
- Use
.clone()
if you need to duplicate heap data
Ownership may feel strict at first, but it prevents entire classes of bugs — no memory leaks, no crashes, no surprises 🦀✨
Up next: References & Borrowing, where we share data without transferring ownership!