Sub topic 3
Scope and Automatic Cleanup with Drop
This chapter assumes you know basic Rust syntax, can run a program with cargo run, and know the stack/heap distinction from the earlier chapters. You should also have seen the three ownership rules. The third rule says that when the owner goes out of scope, the value is dropped. Here you will see exactly what "dropped" means, when it happens, and in what order.
Scope decides when cleanup happens
A scope is the region of code where a variable is valid. In Rust, a scope usually starts at a let binding and ends at the closing brace of the block that contains it. When execution reaches that brace, Rust runs cleanup code for every value still owned by variables in the block. The compiler inserts this cleanup at compile time, so there is no garbage collector and no runtime tracking of who is still using the value.
For a String or Vec, the cleanup frees the heap buffer. For a file handle, it closes the file. For a MutexGuard, it releases the lock. The same mechanism handles all three, which is why Rust code rarely needs explicit close() or free() calls. C++ programmers will recognize this pattern as RAII (resource acquisition is initialization).
The Drop trait
The Drop trait lets a type run its own code during cleanup. It has one method, drop(&mut self). You can implement it to make the timing visible:
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn main() {
let _a = Noisy("a");
{
let _b = Noisy("b");
println!("inner scope ends");
}
println!("main ends");
}This prints:
inner scope ends
dropping b
main ends
dropping a_b lives in the inner block, so it is dropped at that block's closing brace. _a lives until the end of main.
Two details are worth knowing:
droptakes&mut self, notself. After your method returns, the compiler still drops each field of the value. You do not free fields by hand.- You rarely implement
Dropyourself. Most types get correct cleanup automatically because their fields already know how to clean up. ImplementDropwhen the type owns something Rust cannot free by itself, such as a raw pointer, a file descriptor from a C library, or a log entry you want written on exit.
Drop order
Order matters when one resource depends on another, for example a lock guard and the data it protects. Rust's rules are fixed and predictable:
| Situation | Drop order |
|---|---|
| Local variables in one scope | Reverse of declaration (last declared, first dropped) |
| Fields of a struct or tuple | Declaration order (first field, first dropped) |
| Elements of a `Vec` or array | From index 0 upward |
| Temporaries in an expression | At the end of the enclosing statement |
Locals drop in reverse because later variables may hold references to earlier ones. Dropping the later ones first keeps those references valid until they are gone. Fields do not need this rule, so they go in the order written.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
struct Pair {
first: Noisy,
second: Noisy,
}
fn main() {
let _x = Noisy("x");
let _y = Noisy("y");
let _p = Pair {
first: Noisy("p.first"),
second: Noisy("p.second"),
};
println!("end of main");
}The output is:
end of main
dropping p.first
dropping p.second
dropping y
dropping x_p was declared last, so it goes first. Pair has no Drop implementation of its own, but its fields are still dropped in order.
Dropping early with std::mem::drop
Sometimes you want a value gone before the scope ends, for example to release a lock sooner. You cannot call value.drop() directly. The compiler rejects it, because it would run again at the end of the scope and free things twice. Instead, call the standard library function drop, which is in the prelude:
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn main() {
let early = Noisy("early");
let late = Noisy("late");
drop(early);
println!("after explicit drop");
println!("still holding {}", late.0);
}The output is dropping early, after explicit drop, still holding late, dropping late.
std::mem::drop is almost trivial. It takes its argument by value, which moves ownership into the function, and then the function body ends. The parameter goes out of scope and the value is dropped. This is the move rule from the next chapter doing the work.
Moved values are not dropped twice
Drop runs once, for the final owner. If a value is moved, the old variable is no longer responsible for it:
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn consume(n: Noisy) {
println!("consuming {}", n.0);
}
fn main() {
let a = Noisy("a");
let b = Noisy("b");
consume(a);
println!("after consume");
println!("b is {}", b.0);
}The output is consuming a, dropping a, after consume, b is b, dropping b. The value a is dropped when consume returns, not at the end of main. If a move happens only on some paths (inside an if, say), the compiler keeps a hidden flag that records whether the value is still owned. It checks the flag at scope end, so you still get exactly one drop.
Edge cases
Some cases surprise people who assume a variable's lifetime is always its whole block.
- Shadowing does not drop. Writing
let s = Noisy("one"); let s = Noisy("two");creates a second variable. The first still exists, hidden, and is dropped at scope end along with the second, in reverse order. _drops immediately,_namedoes not.let _ = Noisy("t");does not bind the value to anything, so it is dropped at the end of that statement.let _g = Noisy("g");binds it, so it lives until scope end. This matters for lock guards.let _ = mutex.lock();releases the lock instantly.- Temporaries die at the semicolon. In
Noisy("t").0.len();theNoisyis dropped when the statement ends. - Panics still drop. By default a panic unwinds the stack, running
dropfor every live value on the way out. If you build withpanic = "abort", the process exits without running them. - Cleanup is not guaranteed.
std::mem::forget(value)skips the drop on purpose. Reference cycles built withRcalso leak, and so does a process killed by a signal. TreatDropas reliable for ordinary resource cleanup, but do not depend on it for safety invariants. CopyandDropare exclusive. A type that implementsDropcannot also implementCopy. A bitwise copy would produce two values that each try to clean up the same resource.
Exercise
What does this program print, in order? struct Noisy(&'static str); impl Drop for Noisy { fn drop(&mut self) { println!("dropping {}", self.0); } } fn main() { let a = Noisy("a"); let = Noisy("b"); let _c = Noisy("c"); println!("end"); }
Show answer
It prints "dropping b", "end", "dropping c", "dropping a". The pattern _ does not bind, so "b" is dropped at the end of its own statement. The two named variables live to the end of main and drop in reverse declaration order, so "c" goes before "a".