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
dropis called automatically, in reverse creation order.- This is the pattern behind file handles and lock guards.
std::mem::dropends a value's life early.
Keywords and builtins used here
DropGuarddropfnforimplletmainmutselfstaticstrstruct
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.
Step 4 of 4 in Operators & access, step 15 of 19 in Traits & generics.