Sub topic 3
Scope and automatic cleanup with Drop
This chapter assumes you can write basic Rust (variables, functions, structs), run programs with cargo, and know the difference between the stack and the heap. It builds on the ownership rules from the previous chapter. The third rule says that when the owner goes out of scope, the value is dropped. Here you see how that happens.
Scope decides when cleanup runs
A scope is a region of code, usually a pair of braces, in which a variable is valid. A variable becomes valid where it is declared. It stops being valid at the closing brace of its scope. At that point Rust calls a cleanup function named drop on the value. You never write that call yourself.
Languages like C++ call this idea RAII (resource acquisition is initialization). Languages with a garbage collector run cleanup at some later, unpredictable time. In Rust the moment is known at compile time.
The Drop trait
A trait is a set of methods a type can implement. The Drop trait has one method, drop, which runs just before the value's memory is released. Types like String, Vec, and Box implement it to free their heap memory. You can implement it for your own types to close files, release locks, or log events.
This program makes the order 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");
}The output is:
inner scope endsdropping bmain endsdropping a
The value b is dropped at the end of the inner block, before main finishes. The value a is dropped when main ends.
Order of drops
Several values in one scope are dropped in the reverse order of their declaration. The last variable declared is dropped first. This is safe because a later value may hold a reference to an earlier one, so the earlier one must stay alive longer. The fields of a struct are dropped after the struct's own drop runs, in the order the fields are declared.
Common errors
- Calling
dropdirectly. Writingvalue.drop()is a compile error (E0040), because Rust would then drop the value a second time at scope end. To clean up early, call the standard library functionstd::mem::drop(value). It is in the prelude, sodrop(value)works. It takes ownership of the value and lets it go out of scope at once. - Assuming a moved value is dropped in its old scope. If a value is moved to another owner, it is dropped when the new owner's scope ends. The next chapter covers moves.
- Expecting
_to behave like_name. A variable named_blives until the end of its scope. The bare patternlet _ = Noisy("x");drops the value immediately, because nothing binds it.
Exercise
A scope declares let _x = Noisy("x"); and then let _y = Noisy("y");. In what order do the "dropping" messages print, and why?
Show answer
"dropping y" prints first, then "dropping x". Values are dropped in reverse order of declaration, so a later value that might borrow an earlier one is cleaned up before the earlier one.
Exercise
What is the difference between let _ = Noisy("p"); and let _p = Noisy("p"); in terms of when the value is dropped?
Show answer
With let _ =, the value is dropped immediately at the end of that statement, because no variable owns it. With let _p =, the variable owns the value, so it is dropped at the end of the enclosing scope.