-
Notifications
You must be signed in to change notification settings - Fork 0
The Basics of Ownership
Let's take a look at rules 1 and 2:
Rule 1, every value we create inside of a Rust program, is going to be owned by a single variable at a time. Rule 2, reassigning the value to another variable moves the value. Whenever we move a value, the old variable can't be used to access the value anymore.
Let's write out a quick example to investigate these rules a bit.
fn main() {
let bank = Bank::new();
let other_bank = bank;
println!("{:#?}", bank);
}
The above is an example of violating rules 1 and 2.
Somewhere in memory we are creating a new value, here its the 'bank' value. So somewhere in memory is an instance of our bank struct and we want to work with it in some kind of way.
Now lets think about all the different locations inside this main
function where we can assign this 'bank' value to. In this case I think there are two locations where can assign that value. The first is the bank binding and the second is the other_bank binding.
The next thing I want to do is imagine what happens behind the scenes, when we run this code line by line.
When this function runs, we create our bank value and assign it to the bank binding. At that point in time, the bank binding is the owner of the bank value or the value is owned by the bank binding. At this point in time the bank value can only be owned by a single binding.
The second line of code says take whatever value the bank binding owns and move it to the other_bank binding. So we are executing a move of this value from bank binding to other_bank binding which leaves the original bank binding with no value.
Then when we go to println!()
, we are saying I want to print whatever value is right there...study the diagram below to see what there we are referring to:
There is no value there!
So we end up getting an error.
So every value is owned by a single variable at a time. Then whenever we reassign that value to another variable, the value moves and the old variable cant't be used to access the value anymore.
Structs and vectors can also own values as well.