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

I understand that when a variable whose type implements Drop falls outside the scope, a function call fn drop(&mut self) is inserted and a newly created mutable reference to the variable leaving the scope is passed.

However, how is this possible in cases where a variable is immutable, and it would be illegal to borrow it with variability? Here is an example of what I am saying:

 fn main() { let x = vec![1, 2, 3]; let y = &mut x; } 

Which causes the following error: cannot take the immutable local variable x as mutable as expected.

Something similar should happen when x is dropped because Drop expecting a volatile link.

+5
source share
1 answer

The owner of the variable gets the opportunity to determine the variability when creating a variable binding, this is not an integral part of the value itself:

 fn main() { let x = vec![1, 2, 3]; let mut z = x; let y = &mut z; } 

You may think that this happens when the last variable binding with the programmer’s name resets the ownership of the variable. The Magic Drop Fairy takes responsibility for your now unnecessary variable and uses mutable binding. Then Drop-fairy can call Drop::drop before doing the last magic to free up the space taken by the element itself.

Please note that Drop-fairy is not a true Rust concept yet. This RFC is still in a very advanced stage.

+7
source

All Articles