Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a destructor call `fn drop(&mut self)` call inserted when the owning variable is immutable?

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.

like image 552
corazza Avatar asked Jul 23 '15 20:07

corazza


1 Answers

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.

like image 184
Shepmaster Avatar answered Oct 20 '22 22:10

Shepmaster