Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading