The relationship between Drop and memory collection


struct CustomSmartPointer {
data: String,

impl Drop for CustomSmartPointer {
fn drop(&mut self) {
println!(“Dropping CustomSmartPointer with data {}!”,;
I implement the Drop of the structure, but there is no real operation memory, so after the variable is out of scope, will the memory really be recycled?



Yes, memory will be freed automatically in your case. It’s freed after the call to the drop method. It’d also be freed if you don’t implement Drop.

Rust will free memory for you whenever it can. You have to try hard to stop it, e.g. using Rc and creating a reference loop is one of few ways of accidentally leaking memory in Rust. In general you don’t need to worry about freeing memory yourself.

1 Like


It’s the implementation of Drop for String that cleans up Your implementation of Drop is for any special handling you might have to do for CustomSmartPointer beyond what String requires, but the data field (and any other Drop-implementing fields) will still be dropped afterward in the usual way.

1 Like