Bindings in Rust: Much More Than Just Variables
Ownership, move, and copy
The French version of this page is available here
This post is the third episode of a series of 4. If needed, start with episode 1. The list of episodes is at the end of the page.
TL;DR
- Ownership rule : Each concrete instance has a single owner at any given time and is automatically dropped when that owner goes out of scope.
- For a type that does not implement the
Copytrait (String,Vec<T>…),x = yis a move: afterward,yis no longer usable. - Passing a
Vec<T>to a function only pushes its control structure onto the stack, whatever the amount of data. - The new owner does what it wants: it can requalify the binding as
mut. That’s exactly whatfn fill_vec(mut vec: Vec<i32>)does.
Table of Contents
- Where Are We?
- Second line of code
- Study of the fill_vec() function
- The solution with associated comments
Where Are We?
As a reminder, here is the code of the Rustlings exercise move_semantics3.rs that runs through the whole series:
// TODO: Fix the compiler error in the function without adding any new line.
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
vec.push(88);
vec
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn move_semantics3() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
assert_eq!(vec1, [22, 44, 66, 88]);
}
}
In episodes 1 and 2 we only studied the first line of the function move_semantics3(). We concluded that vec0 is an immutable binding that binds the name vec0 to the complete state of a concrete instance of a type Vec<i32>, that mutability is a property of the binding, and that a Vec<T> is made of a control structure (PLC) on the stack and of data on the heap.
Second line of code
Here is the line that interests us:
let vec1 = fill_vec(vec0);
And I put it face to face with the function fill_vec()
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {...}
Now, in order to move forward, I’ll give you THE ownership rule of Rust:
Ownership Rule
Each value has a single owner at any given time and is automatically dropped when that owner goes out of scope.
Print it and post it in your bathroom…
Given what has been said about states and concrete instances, I keep in mind:
Each concrete instance has a single owner at any given time and is automatically dropped when that owner goes out of scope.
Regarding which one to display in your toilets, I’ll let you manage that.
We’re not going to spend 3 hours on it, but hey, some words are important.
1. Each value has a single owner at any given time : This means that during compilation, static code analysis will track which binding owns which concrete instance and call timeout if we try to have two bindings on the same instance. Be careful, we are talking about the owner. I have a Ferrari. Even if I lend it to you, I remain the owner. On the other hand, if I give it to you… “To give is to give, to take away is to steal.” You become the new owner and I no longer have any rights to it.
Be careful… So there’s a subtlety in the previous code and you’ll see that it’s much better when you read it. Indeed, during the call, fill_vec(vec0) what happens? Do we do a pass by value? A pass by reference? Do we give or lend the binding vec0 to the function? Yes, you’re right, it “looks” very much like a pass by value. Everything happens as if we were writing:
vec = vec0
In other words, we will give the binding vec0 to the function fill_vec().
2. and is automatically dropped when that owner goes out of scope : A scope is just an area of code between 2 braces { and }.
Let’s illustrate this using the entire function code move_semantics3() found in section #[test].
fn move_semantics3() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
assert_eq!(vec1, [22, 44, 66, 88]);
}
No worries. Keep in mind that we just said that the binding vec0 was given when calling to fill_vec(). For now, we don’t have the necessary knowledge yet, so I can’t say much about it.
On the other hand, when the fill_vec() returns, what is certain is that the binding vec1 is the owner of a state. There, what I can say is that on the last line, where there is the closing brace, the binding vec1 goes out of scope. And there, automatically, it’s not even up to me to do it, the concrete instance to which vec1 was bound will be deleted from memory.
To be clear, the concrete instance that will be dropped (removed from memory) is the one Vec<i32> that contains the values [22, 44, 66, 88].
So what will happen on the second line?
- the binding
vec0is passed by value to the functionfill_vec()( this is false but we’ll come back to it in 2 min.) - the binding
vec0ceases to be proprietary - the binding
vecfrom thefill_vec()function becomes proprietary - the binding
vec0is invalidated. It remains accessible but we get a compilation error if we try to use it - When the
fill_vec()function returns, the immutable bindingvec1binds the namevec1to the state of a type’s instanceVec<i32>. vec1is the owner of the instance in question
At this point, regarding the binding, you must keep in mind
- It associates a name with the state of an instance of a type
- It adds properties
- of mutability
- of ownership
- …
- Static code analysis ensures that the properties of the bindings are respected.
Study of the fill_vec() function
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
vec.push(88);
vec
}
- The function signature indicates that it has as a parameter a binding
vecwhich is linked to the state of an instance of a typeVec<i32> - The function returns a binding that is bound to the state of an instance of a type
Vec<i32>
The question we can ask ourselves is how, at the time of the function call, the ownership of the binding vec0 is passed to vec. Here, it’s fine because we only have 3 values involved, but if we had a vector of 1 GB of data, we would have a problem. No?
I’ll let you think about it… So?
Remember, Barbara, what circulates through the stack is not the data set itself. Here we have only that, [22, 44, 66] but in fact, thanks to the principle of indirection and the pointer of the control structure, the number of values in the vector does not matter. Only the control structure (PLC) which contains 3 simple type values will pass through the stack. To give you an idea, we can assimilate these 3 data to 3 64-bit integers. It’s super fast and, above all, it’s independent of the number of values in the vector.
On the other hand, you have to keep in mind that it’s not a copy of vec0 in vec but a move (hence the name of the exercise. Clever guys…).
Wait, wait… You can come back to your move story. You went a little too fast. No problem. If I make a copy of simple type variables (trivially copyable, int, float… but not a Vec<T>) the code below works as expected:
fn main() {
let mut my_int1 = 42;
let my_int2 = my_int1;
my_int1+=1;
let my_int3 = my_int1;
assert_eq!(my_int1, 43);
assert_eq!(my_int2, 42);
assert_eq!(my_int3, 43);
}
I copy my_int1 in my_int2 and look, after the copy, I can still increment my_int1 and copy its new value in my_int3. Normal behavior!
OK… Let’s try to do the same thing with a “not so simple” data type ( Vec<T>, String…) :
fn main() {
let my_string1 = String::from("Zoubida");
let mut my_string2 = my_string1; // my_string1 is no longer available
my_string2.push_str(" for ever");
let my_string3 = my_string2; // my_string2 is no longer available
//assert_eq!(my_string1, "Zoubida"); // would panic
//assert_eq!(my_string2, "Zoubida for ever"); // would panic
assert_eq!(my_string3, "Zoubida for ever");
}
As is, the code works, but if you unfortunately delete the comments of the assert line, the compiler jumps down your throat and you die in terrible pain, forgotten by everyone. For example, if I delete the first comment, this is what I read:
Compiling playground v0.0.1 (/playground)
error[E0382]: borrow of moved value: `my_string1`
--> src/main.rs:7:5
|
2 | let my_string1 = String::from("Zoubida");
| ---------- move occurs because `my_string1` has type `String`, which does not implement the `Copy` trait
3 | let mut my_string2 = my_string1; // my_string1 is no longer available
| ---------- value moved here
...
7 | assert_eq!(my_string1, "Zoubida"); // would panic
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
|
= note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
|
3 | let mut my_string2 = my_string1.clone(); // my_string1 is no longer available
| ++++++++
For more information about this error, try `rustc --explain E0382`.
error: could not compile `playground` (bin "playground") due to 1 previous error
Read the compiler messages. No one else will do it for you, and the guys worked their asses off to find a way to help us, so let’s use what they have to offer…
In addition, it’s super clear. The compiler tells us that on line 3 there was a move from the binding my_string1 to the binding my_string2 because the binding my_string1 is linked to the state of an instance of type String and that this data type does not implement a function that would allow it to be copied (it does not implement the Copy trait). So, since we cannot make a copy (but only a move) we have no right to use the binding my_string1 in the assert to compare it to “Zoubida”.
Just to prove I’m trying to be honest… Of course it’s possible to make an explicit copy of a String. You have to use .clone(). The thing here is that since the Copy trait isn’t implemented, by default we make .move().
In fact, at the end of line 3, everything happens as if my_string1 was no longer usable (which it is) and my_string2 had replaced my_string1.
It may be worth remembering that:
| Operation | Syntax | Effect |
|---|---|---|
| Copy | x = y | x and y are usable |
| Move | x = y | x is usable, y is no longer usable |
With these “move” stories covered, I return to the function code
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
vec.push(88);
vec
}
It should be noted that when we arrive in the scope of the function fill_vec() the binding vec0 is no longer the owner. The new owner is vec.
Ah OK, that’s it, I get it. Then we push, we return, and it’s done. Yes, almost, but in the meantime we have a compilation error to deal with. Something like this:
error[E0596]: cannot borrow `vec` as mutable, as it is not declared as mutable
--> exercises\06_move_semantics\move_semantics3.rs:3:5
|
3 | vec.push(88);
| ^^^ cannot borrow as mutable
|
help: consider changing this to be mutable
|
2 | fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
| +++
For more information about this error, try `rustc --explain E0596`.
error: could not compile `exercises` (bin "move_semantics3") due to 1 previous error
Well, of course, no one reads it and everyone complains… Let’s make the effort to read anyway. So, what does it say?
The compiler clearly indicates what is causing the problem: ^^^ cannot borrow as mutable and it tells us that it is vec the one responsible. The icing on the cake is that it even gives us the solution. It says consider changing this to be mutable. And as if that wasn’t enough, it finally gives the solution fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> { with little ones +++ like in a diff to tell us what to add. Isn’t that cute?
Seriously, we’re almost reaching Nirvana. Apart from the word borrow, he’s got it all right. Basically what he’s saying is that vec being an immutable binding, it doesn’t allow the method to be invoked .push() on it. In fact, the latter attempts to modify the state of the concrete instance by adding the value 88 to it.
So what do we do then? Read, I tell you… The compiler gave us the solution. We need to re-qualify the binding vec. Remember, by default everything is immutable. So in the signature:
fn fill_vec(vec: Vec<i32>) -> Vec<i32>
The parameter vec is immutable. We must therefore modify the signature as the compiler suggests:
fn fill_vec(mut vec: Vec<i32>) -> Vec<i32>
* Wait… There’s something I don’t understand… We had an immutable vector at the beginning. We pass it to a function. And hey presto, it can become mutable… That’s not very secure. Is it?*
Let’s go back to the time of the call. What exactly is happening… Remember the rule of ownership: Each value has a single owner at any given time and is automatically dropped when that owner goes out of scope. (Each concrete instance has a single owner at any given time and is automatically dropped when that owner goes out of scope.)
To comply with this rule, we explained that vec0 it was “moved” and no longer usable after the function call. So, don’t worry, vec0 since it’s no longer usable, no one can empty your bank account or steal your digital identity. The “secure” aspect is fine, it’s taken care of.
Next, and this is important to realize. It’s not the data or memory areas that are mutable or immutable. It’s the bindings (mutability is a property of the binding). Typically, the data allocated on the heap at the time of creation of vec0 was “physically” mutable. On the other hand, the compiler monitored the mutability of the binding vec0, it saw that we hadn’t done anything illegal and it worked. Then, we move the binding from vec0 to vec. OK, fine. But if I give you my Ferrari. Nothing prevents you from adding a caravan hook or repainting it yellow. You are the new owner, you do what you want. In other words, it is not forbidden when transferring the binding from vec0 to vec to reclassify it as mutable. We will then have the right to modify the state of the concrete instance at the other end of the binding.
Again, these mutability stories are a property of the binding, not the binding data. However, it is a contract that we sign with the compiler and that we agree to respect. If I say that vec is immutable in the signature, I do not have the right to modify the state of the type instance Vec<i32> (and vice versa if I qualify the binding with mut). It is the compiler, and in particular Rust’s borrow checker, which is responsible for enforcing the law, and we are allowed to say that it is as accommodating as Judge Dredd.
The solution with associated comments
//`vec0` is a mutable binding that links the name ``vec0`` to the complete state of a concrete instance of type ``Vec<i32>``.
// On the heap, the data pointed to by ptr are not copied (and are mutable)
// The `mut` keyword allows the function to modify state of the local concrete instance of type Vec<i32>
// This is possible because fill_vec owns vec_in exclusively
// vec_in is a mutable binding to Vec<i32>, not a mutable Vec<i32> itself
// In the function signature, `mut` works just like it would in: let mut vec_in = ...
fn fill_vec(mut vec_in: Vec<i32>) -> Vec<i32> {
vec_in.push(88); // the state is modified because the data are modified
vec_in // vec_in is moved to the caller
}
// fn main() {
// vec0 is an immutable binding
// A binding associates a name to a value + rules of ownership & borrowing
// mutability is a property of the binding NOT a property of the value (nor the name)
// The term binding in Rust represents a strong contract with the compiler, not just a “classic" variable.
// Here, this means you cannot call vec0.push(...) or reassign vec0
// However, the Vec internally holds a pointer to heap-allocated memory, which is mutable by nature
// Rust allows the ownership of vec0 to be transferred (moved), even if the binding is not mutable
let vec0 = vec![22, 44, 66]; // immutable binding: cannot change vec0 or call vec0.push(...)
// but the heap memory behind it is mutable
// On the heap, data pointed by ptr are mutable
let vec1 = fill_vec(vec0); // vec0 is moved into fill_vec
// vec0 is no longer usable after this point
assert_eq!(vec1, [22, 44, 66, 88]);
// }
Here, to modify the vector, the function fill_vec() becomes its owner and then gives it back. In episode 4 we will see how to lend a binding without giving it away: references, borrowing, and lifetimes.