Drop Trait Cleans Up When Scope Ends
Implement Drop on a guard struct so cleanup code runs when the value leaves scope, either at block end or through an explicit drop call.
Code
struct TempFile {
path: String,
}
impl TempFile {
fn new(path: &str) -> Self {
println!("created {path}");
Self { path: path.to_string() }
}
}
impl Drop for TempFile {
// 值离开作用域时编译器自动插入的清理点,无需手动调用
fn drop(&mut self) {
println!("cleaned up {}", self.path);
}
}
fn main() {
{
let guard = TempFile::new("cache/session.tmp");
println!("using {}", guard.path);
} // guard 在块结束处 drop
println!("scope ended");
let leaked = TempFile::new("cache/leaked.tmp");
drop(leaked); // 也可以用 drop 函数提前显式释放
println!("explicit drop done");
}How the snippet works
Drop Trait Cleans Up When Scope Ends comes down to the functions new, drop and main.
Applying it
The entry-point signature is fn new(path: &str) -> Self
The run emits 5 labeled sections — created, cleaned up, using, scope ended, explicit drop done — one per step.
main sequences new and drop; executing the file runs that flow once.
Statements that matter
fn new(path: &str) -> Self {
println!("created {path}");
Self { path: path.to_string() }
}
impl Drop for TempFile {
// 值离开作用域时编译器自动插入的清理点,无需手动调用
fn drop(&mut self) {
println!("cleaned up {}", self.path);
}
}
Interactive Tools for This Topic
FAQ
- What does Drop Trait Cleans Up When Scope Ends print when run?
- Invoke the file as-is — the `created`, `cleaned up`, `using` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.