0

I have the following piece of code

{
    let mut a = String::from("Foo");
    a = String::from("Bar");
}

I'm wondering when will the first String be freed is it when I assign a to a different String ? or is it when the scope ends ?

Kain
  • 329
  • 1
  • 10
  • Answered here https://stackoverflow.com/questions/56308961/is-destructor-called-on-reassignment-of-a-mutable-variable – ricosrealm Dec 14 '22 at 06:25

1 Answers1

2

You can easily test this:

struct B(&'static str);

impl Drop for B {
    fn drop(&mut self) {
        println!("{} B dropped", self.0)
    }
}

fn main() {
    {
        let mut b = B("first");
        println!("{} B created", b.0);
        b = B("second");
        println!("{} B reasigned", b.0);
    }
}

This outputs:

first B created
first B dropped
second B reasigned
second B dropped

So the first instance of B is dropped when the variable is re-assigned. The second one is dopped at the end of the function.

Playground link to try it yourself

cafce25
  • 15,907
  • 4
  • 25
  • 31
mousetail
  • 7,009
  • 4
  • 25
  • 45