0

What happens with the content of "string 1 ..." when i add "string 2" to s? is it automatically freed from the memory?

fn main() {
    let mut s = String::from("string 1");
    s.push_str(" doing something with string 1");
    s = String::from("string 2"); // Adding new data and making s the owner
    println!("s: {}", s);
}
  • 3
    In short - yes. Before assigning the new value to the `String` the destructor is run on the old value, and its memory is thereby freed. – user4815162342 Aug 20 '21 at 18:51
  • 2
    Similar: [Does Rust free up the memory of overwritten variables?](https://stackoverflow.com/q/48227347/3650362) (but that OP is also confused about the difference between shadowing and mutation) – trent Aug 20 '21 at 18:51

0 Answers0