Drop as destructor
Drop is Rust's destructor trait. When a value goes out of scope, the compiler inserts a call to Drop::drop and then drops each field. You use it to release sockets, files, and other resources that are not just memory.
Detailed Explanation
C++ programmers write a destructor ~Session(). Java programmers have finalize (and are told not to use it) plus try-with-resources. Rust's answer is the Drop trait. If Session implements Drop, then at the end of the owning scope the compiler calls Drop::drop(&mut self) before the fields themselves are dropped. You do not call drop yourself as a method; the language does.
This is RAII, the same idea as C++: resource acquisition is tied to a value's lifetime, and release is tied to its destruction. A File closes the file descriptor in Drop. A MutexGuard unlocks the mutex in Drop. A JoinHandle detaches or joins according to its type. You get the cleanup on every exit path — return, ?, panic unwinding — without a finally block.
Drop is not for reclaiming the struct's own heap buffers. String and Vec already free their allocations in their own Drop impls. You write Drop when your type owns something the language does not know about: a raw file descriptor from libc, a registration in a global map, a background thread you must signal. If the fields can clean themselves, you write no Drop at all. That is the rule of zero, same as modern C++.
Order is defined. Fields are dropped in declaration order after your Drop::drop returns. If drop needs a field, it can still use it; the field has not been dropped yet. You cannot take a field out by value inside drop unless you wrap it in Option and take it, because drop receives &mut self, not self. Moving out would leave a hole the compiler would then try to drop.
You can run a destructor early with std::mem::drop(value), which is an ordinary function that takes ownership and lets the value go out of scope at the call. You cannot prevent a destructor except by std::mem::forget or ManuallyDrop, both of which leak the resource on purpose and are the tools you use when ownership is transferring to C or to a custom allocator.
What it costs: a Drop impl makes the type !Copy (you cannot copy something that has a unique cleanup) and can inhibit some moves in the compiler. A panic inside Drop during an existing panic aborts the process. Keep destructors short and infallible.
When you reach for Drop: a type that owns a resource with a mandatory teardown. When you do not: plain data structs. Do not use Drop as a "finalize" hook for logging or metrics; that runs at surprising times and on panic paths.
Code Examples
struct SessionGuard {
user_id: u64,
}
impl Drop for SessionGuard {
fn drop(&mut self) {
// Runs when `guard` leaves scope, including after `?` or a panic.
println!("release {}", self.user_id);
}
}
fn main() {
{
let _guard = SessionGuard { user_id: 17 };
println!("inside"); // prints: inside
} // prints: release 17
}Common Gotchas
You cannot move fields out of `&mut self` in `drop`
wrap a field in `Option` and `take()` it if teardown needs ownership.
A panic in `Drop` during unwinding aborts
destructors must not panic. If cleanup can fail, log and continue; do not `unwrap`.
`forget` skips `Drop`
the resource leaks. Use it only when something else, such as a C caller, has taken over ownership.