Ownership in Rust
Ownership is Rust’s most unique feature that enables memory safety without a garbage collector. Every value in Rust has a single owner, and when the owner goes out of scope, the value is dropped.The Three Rules of Ownership
Move Semantics
When you assign a value to another variable, ownership is moved by default for heap-allocated types likeString.
What Happens During a Move?
- The ownership of the
Stringvalue transfers frommy_nametonew_variable my_namebecomes invalid and cannot be used anymore- Only
new_variablecan now access the string data - When
new_variablegoes out of scope, the memory is freed
Cloning Values
If you want to keep using the original variable, you need to explicitly clone the data:Cloning creates a deep copy of the data. Both
my_name and _new_variable now own separate copies of the string “Maysam” in memory.Move vs Clone: When to Use Each
When values are moved
When values are moved
- Heap-allocated types like
String,Vec,Box, etc. - Assignment:
let b = a; - Passing to functions:
some_function(a); - Returning from functions
When values are copied (not moved)
When values are copied (not moved)
- Stack-only types that implement the
Copytrait - Integers:
i32,u32,i8, etc. - Floats:
f32,f64 - Booleans:
bool - Characters:
char - Tuples containing only
Copytypes
When to use clone()
When to use clone()
- When you need both variables to own their own copy of the data
- When you want to pass data to a function but still use it afterwards
- Be aware: cloning can be expensive for large data structures
Common Ownership Mistakes
Key Takeaways
Next Steps
Now that you understand ownership, learn about:- Data Types - Which types are
Copyand which are not - Rock Paper Scissors - Apply ownership concepts in a real project