Welcome! Today, we will navigate the realm of variable ownership in Rust. This principle forms the crux of Rust's performance and safety. To visualize this, consider how you solely possess a book before handing it to a sibling. Rust variables adhere to a similar convention. We'll delve into Copy
and non-Copy
types, understand variable ownership within functions.
Variable ownership is the star feature of Rust that differentiates it from other languages. The three rules of ownership are:
-
Each value in Rust has a variable that’s called its owner. This means that there's always one and only one variable bound to any given piece of data. There can only be one owner at a time.
-
When you assign the value of one variable to another, the first variable will no longer hold that value if its type does not implement the
Copy
trait. We could say it's a bit like passing a baton in a relay race! -
When the owner goes out of scope, the value will be dropped. This means once the variable that owns the data is done (like at the end of the function or a block of code), Rust automatically cleans up and frees the memory associated with that data. It's like when you're done reading a library book and return it, the book is no longer in your possession and can be borrowed by someone else.
Rust features the Copy
trait for types of a fixed size that can be safely duplicated. When Copy
types are assigned, the data is reproduced.
