-2

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?

mcarton
  • 21,161
  • 5
  • 54
  • 63

1 Answers1

0

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

mcarton
  • 21,161
  • 5
  • 54
  • 63
Florian Weimer
  • 27,114
  • 3
  • 27
  • 69