Sub topic 8
Drop: cleanup when a value goes out of scope
This chapter assumes you know Rust ownership and moves, basic traits, and the difference between stack and heap memory. It covers the Drop trait, the exact order in which values are dropped, and the ways that order can surprise you.
What Drop does
Rust frees memory without a garbage collector. The compiler knows when each owner goes out of scope and inserts cleanup code at that point. The Drop trait lets your own types add code to that cleanup step.
The trait has one method:
trait Drop {
fn drop(&mut self);
}The compiler calls drop automatically, once, just before the value's memory is released. This is how Box<T> frees its heap allocation. It is also how Rc<T> decrements its reference count, and how a file handle or lock guard releases its resource. Tying cleanup to scope is often called RAII (resource acquisition is initialization).
You only implement Drop when your type owns something the compiler cannot free on its own, such as a file descriptor, a network connection, or a lock. Plain fields like integers and Strings are cleaned up without any help.
A first example
This program uses a type that prints a message when it is dropped. The explicit drop(b) call is explained below.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn main() {
let _a = Noisy("a");
let b = Noisy("b");
drop(b);
println!("end of main");
}The output is:
dropping b
end of main
dropping ab is dropped early because drop(b) moves it into std::mem::drop, which takes ownership and returns. The value goes out of scope at the end of that call. _a lives until main ends, so its message prints last.
Drop order
Drop order is deterministic. Learn these rules, because they matter when values depend on each other.
- Local variables are dropped in reverse order of declaration.
- Fields of a struct are dropped in declaration order, after the struct's own
dropmethod has run (if it has one). - Elements of a
Vecor array are dropped in index order. - Temporaries are dropped at the end of the statement that created them.
The following program shows rules 1 and 2. Pair has no Drop implementation itself, but its fields do.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
struct Pair {
first: Noisy,
second: Noisy,
}
fn main() {
let _x = Noisy("x");
let _y = Noisy("y");
let _pair = Pair {
first: Noisy("pair.first"),
second: Noisy("pair.second"),
};
println!("end of main");
}The output is:
end of main
dropping pair.first
dropping pair.second
dropping y
dropping x_pair was declared last, so it is dropped first. Inside it, first is dropped before second.
Reverse order is deliberate. A later variable may hold a reference to an earlier one, so the earlier one must outlive it.
Moves and drops
A moved value is dropped by its new owner, not by the old one. Rust tracks this at compile time, so a value is never dropped twice.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn consume(n: Noisy) {
println!("consuming {}", n.0);
}
fn main() {
let a = Noisy("a");
consume(a);
println!("after consume");
}The output is:
consuming a
dropping a
after consumeThe value is dropped at the end of consume, because the parameter n owns it there. By the time main prints its last line, a is already gone.
Dropping early
You cannot call value.drop() yourself. The compiler rejects it with error E0040 ("explicit use of destructor method"). If it allowed the call, the automatic drop at scope end would run the destructor a second time (a double free).
To release something early, call the standard library function std::mem::drop, as the first example did. It is in the prelude, so you write drop(value). The function is almost empty. It takes ownership of its argument and returns, so the argument goes out of scope immediately. This is the usual way to release a lock early or to close a file before the end of a long function.
The underscore pitfall
The names _ and _name behave differently, and the difference affects drop timing.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn main() {
let _ = Noisy("ignored");
println!("after ignored");
let _kept = Noisy("kept");
println!("after kept");
}The output is:
dropping ignored
after ignored
after kept
dropping keptlet _ = expr; does not bind the value to anything, so the temporary is dropped at the end of that statement. let _kept = expr; binds it to a variable, so it lives until the end of the scope.
Rules and limits
droptakes&mut self, notself. You can read and modify the value during cleanup, but you cannot move fields out of it.- A type cannot implement both
DropandCopy. A bitwise copy would lead to the same resource being released twice. dropreturns(). It cannot report an error. If cleanup can fail (for example, flushing a buffered file), offer an explicitclosemethod that returns aResult, and treatDropas the best-effort fallback.- Avoid panicking inside
drop. If it panics while the thread is already unwinding from another panic, the process aborts. - Drops also run during panic unwinding. That is why a lock guard unlocks even when the code holding it panics. They do not run if the program aborts or calls
std::process::exit. std::mem::forget(value)takes ownership and skips the destructor. It is safe, because leaking memory does not violate memory safety. Reference cycles (a later chapter) leak memory in the same way.
How this connects to smart pointers
Every smart pointer in this tutorial relies on Drop.
| Type | What its drop does |
|---|---|
| `Box<T>` | Drops the `T`, then frees the heap allocation |
| `Rc<T>` | Decrements the strong count; drops the `T` only when the count reaches zero |
| `RefCell<T>` borrow guards | Release the borrow, so a later `borrow_mut` can succeed |
| `MutexGuard<T>` | Unlocks the mutex |
The RefCell row is why the runtime borrow check in a later chapter works at all. A Ref or RefMut guard marks the cell as borrowed while it exists. Dropping the guard clears the mark. When you see a BorrowMutError panic, a guard you thought was gone is usually still in scope.
Check your understanding
Predict the output of this program before you run it.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn main() {
let a = Noisy("a");
let b = Noisy("b");
let c = Noisy("c");
drop(b);
let _ = Noisy("d");
println!("end");
}Exercise
What does the program above print, in order, and why is each line printed where it is? (The variable a is declared but never used again; ignore the compiler's unused-variable warnings.)
Show answer
It prints "dropping b", "dropping d", "end", "dropping c", "dropping a". drop(b) moves b into std::mem::drop, so b is dropped immediately. let _ = Noisy("d") binds nothing, so the temporary is dropped at the end of that statement, before "end" prints. At the end of main, the remaining locals are dropped in reverse declaration order, so c goes before a.
Exercise
Why does Rust refuse to let you call value.drop() directly, and what should you write instead to release a value early?
Show answer
The compiler would still run the destructor again at the end of the scope, which would release the same resource twice (a double free). Call drop(value) (std::mem::drop) instead. It takes ownership of the value, so the value is dropped when the call returns, and the compiler knows not to drop it again.