Ownership

Loading concept...

πŸŽ’ Ownership in Rust: The Backpack Adventure

Imagine you have a magical backpack. This backpack can only belong to ONE person at a time. That’s Rust’s ownership!


🌟 The Big Idea

In Rust, every piece of data has one owner. Think of it like your favorite toy β€” only YOU can play with it right now. If you give it to a friend, now THEY own it, and you can’t use it anymore.

This simple rule makes Rust super fast and super safe. No fighting over toys. No broken toys. Everyone knows who owns what!


🧠 Memory Management Basics

What IS Memory?

Think of your computer’s memory like a giant toy shelf.

  • πŸ“¦ Every toy (data) needs a spot on the shelf
  • 🏷️ Each spot has an address (so we can find it)
  • 🧹 When you’re done, the spot needs cleaning for new toys

The Problem: Who cleans up?

Language Who Cleans? Good/Bad
C/C++ You do! 😬 Easy to forget
Java/Python A robot (GC) 🐌 Can be slow
Rust Automatic rules ⚑ Fast + Safe!

Rust uses ownership rules to know EXACTLY when to clean up. No robot needed. No forgetting. Just rules!


πŸ“š Stack vs Heap: Two Toy Shelves

Your computer has TWO shelves for toys:

πŸ₯ž The Stack (Fast Shelf)

Like a stack of pancakes! πŸ₯ž

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Plate 3   β”‚ ← Last in, first out!
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚   Plate 2   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚   Plate 1   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  • βœ… Super fast to add/remove
  • βœ… Fixed size items only
  • βœ… Automatically cleaned when done
  • πŸ“Œ Stores: numbers, booleans, fixed arrays

Example:

let x = 5;      // On the stack!
let y = true;   // On the stack!
let z = 3.14;   // On the stack!

πŸ—ƒοΈ The Heap (Big Storage Room)

Like a big warehouse with boxes! πŸ“¦

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  πŸ“¦ Box A (at spot 101)  β”‚
β”‚  πŸ“¦ Box B (at spot 205)  β”‚
β”‚  πŸ“¦ Box C (at spot 342)  β”‚
β”‚        ...more room...   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  • βœ… Can store ANY size
  • βœ… Flexible and big
  • ⚠️ Slower to access
  • πŸ“Œ Stores: Strings, Vectors, complex data

Example:

let s = String::from("hello");
// "hello" is in the heap
// s holds the address (pointer)

Quick Comparison

Feature Stack πŸ₯ž Heap πŸ—ƒοΈ
Speed ⚑ Super fast 🚢 Slower
Size Fixed only Any size
Cleanup Automatic Needs tracking
Example let x = 5 String::from()

🚚 Move Semantics: Passing the Toy

Here’s where the magic happens!

The Rule

When you give something to someone else, you lose it.

Story Time: 🎈

Little Rustie has a balloon (String). She gives it to her friend Ferris.

let balloon = String::from("red");
let ferris_balloon = balloon;
// balloon is GONE! Ferris owns it now.
graph TD A["Rustie has balloon"] --> B["Gives to Ferris"] B --> C["Ferris owns balloon"] B --> D["Rustie has NOTHING"] style D fill:#ff6b6b style C fill:#4ecdc4

Why? Because strings live on the heap. If both could use it, they might fight! Rust prevents this.

What happens if Rustie tries to use it?

let balloon = String::from("red");
let ferris_balloon = balloon;
println!("{}", balloon); // ❌ ERROR!
// "balloon" was moved!

This is called a move. The data moved to a new owner!


πŸ“‹ Copy Trait: Making Photocopies

Some small, simple things can be copied instead of moved!

The Rule

Small, simple data on the stack gets copied automatically.

Story Time: πŸ“

Little Rustie has a sticker with the number 5. She gives Ferris a copy β€” but she KEEPS her sticker too!

let x = 5;
let y = x;  // Copy! Both have 5!
println!("x = {}", x); // βœ… Works!
println!("y = {}", y); // βœ… Works!
graph TD A["x = 5"] --> B["Copy to y"] B --> C["x still = 5"] B --> D["y = 5"] style C fill:#4ecdc4 style D fill:#4ecdc4

What Types Have Copy?

Type Copy? Why?
i32, u64, etc. βœ… Yes Small, stack-only
bool βœ… Yes Just 1 bit!
f64 βœ… Yes Fixed size
char βœ… Yes Single character
String ❌ No Lives on heap
Vec<T> ❌ No Lives on heap

Easy Rule: If it’s a simple number or boolean, it copies. If it’s big or on the heap, it moves!


🧬 Clone Trait: Making a Real Copy

What if you WANT to copy something big? Use clone!

The Rule

Clone makes a FULL copy of data β€” even heap data!

Story Time: 🎨

Rustie has a beautiful painting (String). She doesn’t want to give it away, but Ferris wants one too. So she paints an EXACT copy!

let painting = String::from("Starry Night");
let copy = painting.clone();
// Now BOTH have their own painting!
println!("{}", painting); // βœ… Works!
println!("{}", copy);     // βœ… Works!
graph TD A["Original Painting"] --> B[".clone"] B --> C["Original: Still there!"] B --> D["Copy: Brand new!"] style C fill:#4ecdc4 style D fill:#667eea

Copy vs Clone

Copy Clone
How Automatic You call .clone()
Speed ⚑ Instant 🐌 Takes time
Memory Same spot New memory allocated
Types Stack only Any type

Example comparing both:

// COPY (automatic for i32)
let a = 10;
let b = a;  // Copied automatically!

// CLONE (explicit for String)
let s1 = String::from("hello");
let s2 = s1.clone();  // Must call .clone()

🎯 Putting It All Together

Let’s trace through a complete example:

fn main() {
    // Stack data - will COPY
    let age = 25;
    let age_copy = age;
    println!("Ages: {} {}", age, age_copy);
    // βœ… Both work! Integers copy.

    // Heap data - will MOVE
    let name = String::from("Rustacean");
    let moved_name = name;
    // println!("{}", name); // ❌ Would fail!
    println!("Name: {}", moved_name);
    // Only moved_name works now.

    // Heap data - use CLONE to keep both
    let greeting = String::from("Hello!");
    let greeting_copy = greeting.clone();
    println!("{} {}", greeting, greeting_copy);
    // βœ… Both work! We cloned it.
}

🌈 Summary: The Ownership Adventure

Concept One-Line Summary
Ownership Every value has ONE owner
Memory Stack is fast, Heap is flexible
Stack Small fixed data, auto-cleanup
Heap Big data, needs owner tracking
Move Giving away = losing access
Copy Small stack data auto-duplicates
Clone Explicitly copy anything (slower)

πŸ’‘ Why This Matters

Rust’s ownership system gives you:

  • πŸš€ Speed β€” No garbage collector slowing things down
  • πŸ›‘οΈ Safety β€” No crashes from using deleted data
  • 🧹 Clean code β€” Clear who owns what

You now understand how Rust thinks about memory. You’re already ahead of many programmers!

Next up: Learn how to borrow data without giving it away! πŸŽ‰

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive - Premium Content

Please sign in to view this interactive content and start learning.

Upgrade to Premium to unlock full access to all interactive content.

Stay Tuned!

Interactive content is coming soon.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Cheatsheet - Premium Content

Please sign in to view this cheatsheet and start learning.

Upgrade to Premium to unlock full access to all cheatsheets.

Stay Tuned!

Cheatsheet is coming soon.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Quiz - Premium Content

Please sign in to view this quiz and test your knowledge.

Upgrade to Premium to unlock full access to all quizzes.

Stay Tuned!

Quiz is coming soon.

Flashcard Preview

Flashcard - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Flashcard - Premium Content

Please sign in to view flashcards and reinforce your learning.

Upgrade to Premium to unlock full access to all flashcards.

Stay Tuned!

Flashcards are coming soon.