Ownership Rules
Rust has a special system called ownership that makes your programs safe without needing a garbage collector. It's one of the things that makes Rust unique!
The Three Rules
- Every value in Rust has a single owner (a variable)
- There can only be one owner at a time
- When the owner goes out of scope, the value is dropped (cleaned up)
Moving Ownership
When you assign a String to another variable, ownership moves:
After the move, name can't be used anymore — hero is the new owner. This prevents two variables from trying to clean up the same memory!
Copy Types
Simple types like numbers and booleans are copied instead of moved:
Numbers live on the stack and are cheap to copy, so Rust copies them automatically.
Moving Into Functions
Passing a String to a function also moves ownership:
Borrowing with &
What if you want to use a value without taking ownership? You can borrow it with &:
A borrow is like lending a book to a friend — they can read it, but you still own it!
Mutable Borrowing with &mut
To let a function change a borrowed value, use &mut:
Important rules:
- You can have many
&borrows at the same time - You can have only one
&mutborrow at a time - You can't mix
&and&mutborrows
Clone
If you really need two separate copies of a String, use .clone():
Summary
| Concept | What it does |
|---|---|
| Ownership | Every value has exactly one owner |
| Move | Assigning a String moves ownership |
| Copy | Numbers and bools are copied automatically |
&value | Borrows a value (read-only) |
&mut value | Borrows a value (read & write) |
.clone() | Creates a deep copy of a value |
Now let's practice ownership and borrowing!