Huh?
Rules
From the Rust book:
Each value in Rust has a variable that’s called its owner.
There can only be one owner at a time.
When the owner goes out of scope, the value will be dropped.
Scope
Let's begin with a quick recap of scope. Scope is essentially where an item (function or value) is valid. As an example, look at the code below:
fn main() {
{ // s is not valid here, it’s not yet declared
let mut s = "hello"; // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
s = "bye"; // you will get an error: unresolved name `s`
}Variables are valid when they are in scope and invalid when they are out of scope. Why does this matter? In Rust, when a variable goes out of scope, the memory that it was using is automatically returned.
Moving
If you copy a value into another variable, Rust essentially just moves that value. Take this code for example:
If you run that code, you will get this error message:
That error message lets you know that you can no longer access s1 because you moved it to s2. What if we don't want to do that? We can use the clone method if we want to deep copy:
However, you do not have to clone if you are dealing with integers (or any of the other types that are defined in Data Types). Integers utilize a Copy trait which allows the value to be usable after the assignment.
Why? Because integers are a known size, copies of the actual value are quick to make. Not the same with Strings and HashMaps.
Ownership and Functions
Functions work similarly to variables: if you pass anything (other than the types defined in Data Types that have a pre-defined size), it will change ownership. Take a look at this example:
If you want to play around with it, uncomment out line 6 and see what kind of error you get.
Let's go back to our code from Collections:
This is not really Rust best practice and this code is likely expensive since we are using clone. So let's rewrite it a bit in a slightly more efficient manner.
We're going to dig into that code a bit more in the next section.
Last updated