Suppose I have defined a mutable variable that may be some complex structure containing vectors or other dynamically allocated data with the Drop
trait. On reassigning that variable, is the destructor called immediately after reassignment?
let mut x = some_complex_struct;
while some_condition {
// ...
x = new_complex_struct;
// ...
}
My interpretation is x
gains ownership on new_complex_struct
, its previously owned value becomes unowned, so its destructor would be called right after reassignment. Is my interpretation correct?
My interpretation is
x
gains ownership onnew_complex_struct
, its previously owned value becomes unowned, so its destructor would be called right after reassignment. Is my interpretation correct?
Yes. This can easily be checked:
struct Foo;
impl Drop for Foo {
fn drop(&mut self) {
println!("Foo::drop");
}
}
fn main() {
let mut f = Foo;
for i in 0..5 {
println!("Before {}", i);
f = Foo;
println!("After {}", i);
}
}
Will as expected print:
Before 0
Foo::drop
After 0
Before 1
Foo::drop
After 1
Before 2
Foo::drop
After 2
Before 3
Foo::drop
After 3
Before 4
Foo::drop
After 4
Foo::drop
Destructors in Rust are deterministic, so this behaviour is set in stone.
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