Skip Drop Glue With mem forget
Show drop glue in action and skip it deliberately with std::mem::forget, which consumes a value without running Drop and leaks its heap allocations.
Code
struct Audit {
label: String,
}
impl Drop for Audit {
fn drop(&mut self) {
println!("dropping {}", self.label);
}
}
fn main() {
let a = Audit { label: "normal".into() };
drop(a); // 显式 drop:析构立即执行
let b = Audit { label: "forgotten".into() };
// Drop glue skipped: mem::forget 消费值但不跑析构,堆内存泄漏
std::mem::forget(b);
println!("after forget");
// 值已被消费:再使用 b 是编译错误 E0382
let _c = Audit { label: "scoped".into() };
println!("end of main");
}How it works
One way to read it: the functions drop and main, doing all the work.
Points of care
- No external surface: all behavior comes from the standard library.
Putting it to use
Entry signature: fn drop(&mut self)
Expect labeled output — dropping, after forget, end of main — when the file runs.
The entry point wires drop together — run it once and the whole demo flows.
Core lines
impl Drop for Audit {
fn drop(&mut self) {
println!("dropping {}", self.label);
}
}
Interactive Tools for This Topic
FAQ
- What does Skip Drop Glue With mem forget print when run?
- Invoke the file as-is — the `dropping`, `after forget`, `end of main` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.