Manually Drop Postpones Destruction
Suppress automatic destructors with ManuallyDrop, taking raw ownership of a value so field order or manual drop() controls when resources release.
Code
use std::mem::ManuallyDrop;
struct Connection {
name: String,
}
impl Drop for Connection {
fn drop(&mut self) {
println!("closing {}", self.name);
}
}
fn main() {
// ManuallyDrop 包裹后离开作用域不触发 Drop
let leaked = ManuallyDrop::new(Connection { name: "manual".into() });
println!("scoped end for {}", leaked.name);
// 需要释放时显式调用:drop 时机完全受控
drop(ManuallyDrop::into_inner(leaked));
// into_inner 已把值移出包装,不能重复释放
println!("into_inner consumed the wrapper");
// 对照:普通值在作用域结束才析构,顺序不可控
{
let auto = Connection { name: "auto".into() };
println!("holding {}", auto.name);
}
println!("auto dropped when the block ended");
}Inside the snippet
Every runnable line is contained in the functions drop and main.
What to watch for
- The third-party count is zero; the runtime already has every API used here.
Using it
Entry signature: fn drop(&mut self)
The run emits 5 labeled sections — closing, scoped end for, into_inner consumed the wrapper, holding, auto dropped when the block ended — one per step.
The demo flow inside main is drop — run the file to see it end to end.
Key statements
impl Drop for Connection {
fn drop(&mut self) {
println!("closing {}", self.name);
}
}
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
FAQ
- What does Manually Drop Postpones Destruction print when run?
- Running the file directly is enough — expect labeled output lines such as `closing`, `scoped end for`, `into_inner consumed the wrapper`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.