Rust mutable variable and String

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 ?

>Solution :

You can easily test this:

struct B {
    
}

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

fn main() {
    {
        let mut b = B {};
        println!("B created");
        b = B{};
        println!("B reasigned");
    }
}

This outputs:

B created
B dropped
B reasigned
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

Leave a Reply