`Drop`
Drop runs when a value's owner goes out of scope. The compiler inserts the call; you use it to release files, sockets, and other resources.
Detailed Explanation
At the closing brace, Rust drops locals in reverse declaration order. For each value that implements Drop, it calls drop(&mut self) and then drops the fields. You do not call Drop::drop yourself. std::mem::drop(value) is a function that takes ownership and lets the scope end immediately.
String and Vec implement Drop to free their buffers. File closes the descriptor. MutexGuard unlocks. That is RAII: the type's lifetime is the resource's lifetime. If your fields already clean themselves, do not write Drop. The rule of zero applies.
Inside Drop you have &mut self. You cannot move fields out unless they are Option and you take. A panic in Drop during unwinding aborts the process. Keep destructors short. forget and ManuallyDrop skip Drop; they leak on purpose when ownership moves to C or to a custom allocator.
Drop makes a type !Copy. Implementing Drop is a claim that something unique must happen at the end of life. Two bitwise copies would run that something twice.
When you implement Drop: a resource the language does not know about. When you do not: plain data. When you need early cleanup: drop(value) or a tighter scope, not a manual close method that leaves a zombie value (or pair close with Option so the drop is a no-op).
Drop order of struct fields is declaration order, after your Drop::drop returns. If field A must be dropped before field B, declare A first or wrap B in ManuallyDrop and drop it yourself. This matters for a raw pointer field that must not outlive the allocation field that owns the bytes.
Code Examples
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
fn main() {
let _g = Guard("ada");
println!("body");
} // prints:
// body
// drop adaCommon Gotchas
You cannot move out of `self` in `drop`
Use `Option::take` if teardown needs ownership of a field.
Panic-in-drop during unwind aborts
Destructors must not panic. Log and continue.
`forget` leaks
Use it only when another owner (often C) has taken over.