expression

Release an application resource permit on scope exit

A guard can tie a resource reservation to ownership so early returns release it. This single-threaded Cell model borrows its counter; it does not manage a real OS handle. Real native handles need ownership-aware wrappers, and destructors cannot report cleanup failures through a Result. Expected stdout (not executed): second denied: true after scope: 0 Common mistake: Assuming Drop runs after abrupt termination or using a single-threaded Cell for concurrent reservations. Run only in the isolated fixture runner, not a public code playground.

Formal Syntax & Structure

rust syntaxrust
Drop::drop(&mut self)

Working Example

Example Snippetrust
use std::cell::Cell;struct Permit<'a>(&'a Cell<u32>);impl Drop for Permit<'_> {    fn drop(&mut self) { self.0.set(self.0.get() - 1); }}fn reserve(used: &Cell<u32>) -> Option<Permit<'_>> {    if used.get() >= 1 { return None; }    used.set(used.get() + 1);    Some(Permit(used))}fn main() {    let used = Cell::new(0);    { let _permit = reserve(&used).unwrap(); println!("second denied: {}", reserve(&used).is_none()); }    println!("after scope: {}", used.get());}
Rust Reference