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