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 ?
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 ?
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.