Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is destructor called on reassignment of a mutable variable?

Tags:

rust

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?

like image 290
jam Avatar asked Oct 16 '25 12:10

jam


1 Answers

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?

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.

like image 158
mcarton Avatar answered Oct 19 '25 01:10

mcarton