aurelia
aurelia

Reputation: 677

What happens to the memory that was 'moved into'?

Does rust drop the memory after move is used to reassign a value?

What happens to the string "aaa" in this example?

let mut s = String::from("aaa");
s = String::from("bbb");

I'm guessing that the "aaa" String is dropped - it makes sense, as it is not used anymore. However, I cannot find anything confirming this in the docs. (for example, the Book only provides an explanation of what happens when we assign a new value using move).

I'm trying to wrap my head around the rules Rust uses to ensure memory safety, but I cannot find an explicit rule of what happens in such a situation.

Upvotes: 2

Views: 276

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155363

Move semantics are implicit here. The data in s is initialized by moving from the String produced by String::from("bbb"). The original data stored in s is dropped by side-effect (the process of replacing it leaves it with no owner, so it's dropped as part of the operation).

Per the destructor documentation (emphasis added):

When an initialized variable or temporary goes out of scope, its destructor is run, or it is dropped. Assignment also runs the destructor of its left-hand operand, if it's initialized. If a variable has been partially initialized, only its initialized fields are dropped.

Upvotes: 5

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26569

Yes, assignment to a variable will drop the value that is being replaced.

Not dropping the replaced value would be a disaster - since Drop is frequently used for deallocation and other cleanup, if the value wasn't dropped, you'd end up with all sorts of leaks.

Upvotes: 4

Related Questions