Drop trait for custom cleanup logic
Marcus Chen
Jan 2026
1 tab
struct Logger {
name: String,
}
impl Drop for Logger {
fn drop(&mut self) {
println!("{} is being dropped", self.name);
}
}
fn main() {
let _logger = Logger { name: "MyLogger".to_string() };
println!("End of main");
} // Logger dropped here
1 file · rust
Explain with highlit
The Drop trait runs when a value goes out of scope, similar to destructors in C++. I implement Drop for resource handles: closing file descriptors, releasing locks, or logging cleanup. The drop method takes &mut self and can't fail (no Result). Rust calls Drop automatically; you rarely call it manually (use std::mem::drop() for explicit drops). Drop order is deterministic: values are dropped in reverse order of creation. For async cleanup, Drop can't call async functions, so I use a separate async fn shutdown() method. Drop is essential for RAII (Resource Acquisition Is Initialization), ensuring resources are freed even on panic.