Drop and resource cleanup
Quick answer
Rust normally cleans up owned resources when their owners are dropped. You can explicitly end a value's ownership early with std::mem::drop. This pattern of associating resource cleanup with ownership is called RAII.
Scope and explicit cleanup
For a local String, its buffer is normally freed at the end of its scope. drop(value) consumes a value now; the old binding is unusable for a non-Copy value. Locals in the same scope normally drop in reverse declaration order. Custom destructors are introduced later with the Drop trait; aborts and intentional leaks can prevent cleanup.
fn main() { let temporary = String::from("temporary"); println!("{}", temporary); drop(temporary); println!("next step");}Expected stdout (not executed):
temporarynext stepThe owner is consumed before the next step. The output shows control flow, not measured memory use.
fn main() { let text = String::from("done"); drop(text); println!("{text}");}Expected: compilation fails; exact diagnostic not verified.
The call consumes the String, so the subsequent use is rejected.
Common mistake
drop is not a universal promise that a destructor always runs, and dropping an integer only consumes a copy.
Try it yourself
Explain why releasing a temporary buffer early can be useful before creating a larger one.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Drop and resource cleanup — practice quiz
Choose one answer per question, then review the explanation.
Two local owners x then y are declared in one scope. What is the normal drop order?
What does `drop(s)` do to a non-Copy owned String?
Are destructors guaranteed to run on process abort?