typestar

Drop and RAII in Rust

Drop runs when a value goes out of scope, which is how Rust does cleanup.

struct Guard {
    name: &'static str,
}

impl Drop for Guard {
    fn drop(&mut self) {
        println!("releasing {}", self.name);
    }
}

fn main() {
    let _outer = Guard { name: "outer" };
    {
        let _inner = Guard { name: "inner" };
        println!("inside the block");
    }
    let early = Guard { name: "early" };
    drop(early);
    println!("end of main");
}

How it works

  1. drop is called automatically, in reverse creation order.
  2. This is the pattern behind file handles and lock guards.
  3. std::mem::drop ends a value's life early.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
321
Tokens
100
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 57 seconds.

Type this snippet

Step 4 of 4 in Operators & access, step 15 of 19 in Traits & generics.

← Previous Next →