It is my understanding that when a variable whose type implements Drop
goes out of scope, a call to the fn drop(&mut self)
function is inserted, and passed a newly-created mutable reference to the variable going out of scope.
However, how is that possible in cases where the variable was immutably bound, and it would be illegal to borrow it mutably? Here's an example of what I'm talking about:
fn main() {
let x = vec![1, 2, 3];
let y = &mut x;
}
Which produces the following error: cannot borrow immutable local variable x
as mutable as expected.
Something similar must happen when x
would be getting dropped, because drop
expects a mutable reference.
The owner of a variable gets to decide the mutability when the variable binding is created, it's not intrinsic to the value itself:
fn main() {
let x = vec![1, 2, 3];
let mut z = x;
let y = &mut z;
}
You can think of dropping as happening when the last programmer-named variable binding gives up the ownership of the variable. The magical Drop-fairy takes ownership of your now-unneeded variable, and uses a mutable binding. Then the Drop-fairy can call Drop::drop
before doing the final magic to free up the space taken by the item itself.
Note the Drop-fairy is not a real Rust concept yet. That RFC is still in a very preliminary stage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With