1
struct Item {
    name: String,
}

impl Item {
    fn new(x: &str) -> Item {
        Item { name: String::from(x) }
    }

    fn change_name(&mut self, x: &str) {
        self.name = String::from(x);
    }
}

fn main() {
    let mut item1 = Item::new("Foo");
    item1.change_name("Bar");
}

When I call item1.change_name(), what will happen to the String("Foo") assigned to the name previously. When will drop() be called on the String("Foo")? Will this leak memory?

Wazir Ahmed
  • 99
  • 1
  • 11
  • 1
    Of course there is no leak in this case. Do you imagine a modern language with such a flaw? – Boiethios Nov 21 '19 at 16:04
  • 1
    just test it https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=463feb204a32376690c1cd5da6af8e45 – Stargateur Nov 21 '19 at 16:28

1 Answers1

5

After some research I got the answer.

When a new value is assigned to a variable (by overwriting, not by shadowing) then the old value will be dropped as part of the assignment operation.

Reference

Wazir Ahmed
  • 99
  • 1
  • 11