Memory management Question?

Since rust doesn't have a garbage collection, what would happens to the allocated memory when the variable holds that address and doesn't go out of scope?

For Example:

let mut five = Box::new(5); // LINE 1
five = Box::new(5); // LINE 2

What would happen to the allocated memory in LINE 1 when five doesn't go out of scope?? since five holds a new allocated memory.

The original value will be dropped when it is reassigned, so the LINE 1 box is freed on LINE 2.

1 Like

@cuviper Thanks for the response. Is that same for value type? For example

let st = some_struct::new() // LINE 1; NOT BOXED - VALUE COPY
st = some_struct::new()

is that the same concept which is the original value will be dropped from memory?

Copy values can't have special implementations of Drop, so it's just overwritten. As a side note, your code wouldn't work because you didn't make the variable mutable.

1 Like

Destructors always run when values are destroyed.

1 Like

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.