lifetime
Rust Lifetime constraints during destruction
A destructor may access borrowed fields even after the last explicit use of the containing value. The borrow checker must account for such destruction. A shorter borrow region inferred from ordinary uses does not automatically remove constraints created by Drop. Expected output (not executed): Working Closing job Name: job Why: Dropping report while name is available allows its destructor to read the name. Common mistake: Assuming a reference stored in a type with Drop is no longer needed just because the last explicit method call finished.
Formal Syntax & Structure
rust syntaxrust
impl Drop for Guard<'_> { fn drop(&mut self) { ... } }Working Example
Example Snippetrust
struct Report<'a>(&'a str);impl Drop for Report<'_> { fn drop(&mut self) { println!("Closing {}", self.0); }}fn main() { let name = String::from("job"); let report = Report(&name); println!("Working"); drop(report); println!("Name: {name}");}