Drop Values Early With The Drop Function
drop(value) runs the Drop impl immediately instead of at scope end; Drop::drop cannot be called directly by name.
Code
struct Lease {
name: String,
}
impl Drop for Lease {
fn drop(&mut self) {
println!("releasing lease: {}", self.name);
}
}
fn main() {
let a = Lease { name: String::from("network") };
let b = Lease { name: String::from("disk") };
// drop(value) runs Drop early instead of at scope end
drop(a);
println!("a is released, b still held: {}", b.name);
// Drop::drop cannot be called directly by name; use the free drop function
// to release a value early
drop(b);
println!("all leases released");
}How the snippet works
Read it this way: everything runs through the functions drop and main, doing all the work.
What to watch for
- No dependency machinery at all — no registry file and no lockfile entry.
Applying it
The main signature is written as fn drop(&mut self)
The run emits 3 labeled sections — releasing lease:, a is released, b still held:, all leases released — one per step.
Launch the file; main takes over and steps through drop.
Statements that matter most here
impl Drop for Lease {
fn drop(&mut self) {
println!("releasing lease: {}", self.name);
}
}
Interactive Tools for This Topic
FAQ
- What does Drop Values Early With The Drop Function print when run?
- No setup needed: run the file and look for labeled lines like `releasing lease:`, `a is released, b still held:`, `all leases released` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.