🧠 Ownership in Rust


🪄 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.

rust
Loading…

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:

rust
Loading…

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.

rust
Loading…

📦 Functions and Ownership

Passing ownership into functions follows the same rules:

rust
Loading…

If you want to return ownership, you can!

rust
Loading…

🧬 Cloning (Explicit Copying)

If you want to make a real copy of heap data, use .clone():

rust
Loading…

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!