pointers - How is a destructor call `fn drop(&mut self)` call inserted when the owning variable is immutable? -
it understanding when variable type implements drop
goes out of scope, call fn drop(&mut self)
function inserted, , passed newly-created mutable reference variable going out of scope.
however, how possible in cases variable immutably bound, , illegal borrow mutably? here's example of i'm talking about:
fn main() { let x = vec![1, 2, 3]; let y = &mut x; }
which produces following error: cannot borrow immutable local variable x
mutable expected.
something similar must happen when x
getting dropped, because drop
expects mutable reference.
the owner of variable gets decide mutability when variable binding created, it's not intrinsic value itself:
fn main() { let x = vec![1, 2, 3]; let mut z = x; let y = &mut z; }
you can think of dropping happening when last programmer-named variable binding gives ownership of variable. magical drop-fairy takes ownership of now-unneeded variable, , uses mutable binding. drop-fairy can call drop::drop
before doing final magic free space taken item itself.
note drop-fairy not real rust concept yet. rfc still in preliminary stage.
Comments
Post a Comment