Reputation: 39
Do I need to deallocate memory manually in this case:
let mut s = String::new();
...somecode here...
s = String::new();
and is it the best way to erase content of the string?
Upvotes: -1
Views: 962
Reputation: 33747
In such simple cases, Rust will automatically free memory when it us no longer needed.
If you want to assign a zero-length string to s
, you can use the clear
function:
s.clear();
This preserves the current capacity (and allocation) of the string. The alternative you cited,
s = String::new();
does not do this. Both approaches have their uses, depending on the circumstances. Sometimes, retaining a large string allocation is wasteful (if the string will never grow to this size again).
Upvotes: 1