Newbie Questions:How/When to Release Values on Heap

How or When to Release "abc" on Heap:

fn test() {
let mut s1 = String::from("abc");
println!("{}", s1);
let s2 = String::from("123");
s1 = s2;
println!("{}", s1);

// ...


Rust compiler decides when to free your heap memory on compile time. There is no memory leak on your code. Read this fore more information:

Whether “abc” is released when s1 exits the scope, which can be a long time.

The s1 = s2 line destroys the previous value in s1, deallocating abc.

1 Like

I did not fully understand you, however, if you need to free any heap memory that you own the ownership early, you can use the drop function.:

Sorry for my poor English.
I mean, in java , when line s1=s2; the "abc" has no References and GC comes free "abc".

1 Like
  • Each value in Rust has a variable that’s called its owner .
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value will be dropped.

it seems that s1 can have ownership of both "abc" and "123" at same time?

No. When s1 is set to the new value, the old value is dropped, since it doesn't have any other owner (unless you use something like mem::swap, of course).


If it is a sequence like Vec, it can. But this is not the case here.

In Rust, abc is freed immediately when s1 = s2 runs, whereas in Java it is freed "soon" whenever the GC gets around to it.


Thank you for your explanation. @alice,@Cerberuser ,@eko

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.