Scope and the Drop Trait
In this page:
Automatic Cleanup at End of Scope
Every value's owner has a scope, and when that scope ends, Rust automatically runs cleanup code for the value, freeing any associated memory without any explicit action from you.
Example: Automatic Cleanup at End of Scope
fn main() {
let message = String::from("cleaned up automatically");
println!("{}", message);
} // message is dropped here
Login to try C/C++/Java/PHP code in the editor
Implementing Drop
You can implement the Drop trait for your own struct to run custom cleanup logic, such as printing a message, right when a value of that type goes out of scope.
Example: Implementing Drop
struct Connection {
name: String,
}
impl Drop for Connection {
fn drop(&mut self) {
println!("Closing connection: {}", self.name);
}
}
fn main() {
let _conn = Connection { name: String::from("db") };
println!("Using connection");
}
Login to try C/C++/Java/PHP code in the editor
Drop Order Is Reverse of Declaration
When multiple values go out of scope together, Rust drops them in the reverse order they were declared, similar to unwinding a stack.
Example: Drop Order Is Reverse of Declaration
struct Announcer(i32);
impl Drop for Announcer {
fn drop(&mut self) {
println!("Dropping {}", self.0);
}
}
fn main() {
let _first = Announcer(1);
let _second = Announcer(2);
println!("Both created; watch the drop order below");
}
Login to try C/C++/Java/PHP code in the editor
Forcing an Early Drop
Sometimes you want a value cleaned up before its scope naturally ends. Since you cannot call .drop() directly, the standard library provides std::mem::drop to consume and drop a value early.
Example: Forcing an Early Drop
struct Resource;
impl Drop for Resource {
fn drop(&mut self) {
println!("Resource released early");
}
}
fn main() {
let res = Resource;
println!("About to release early");
drop(res);
println!("Released; rest of main continues");
}
Login to try C/C++/Java/PHP code in the editor
- Manually trying to free or clean up a value yourself instead of trusting Rust's automatic
Dropbehavior. - Assuming
Dropruns in the order variables were created -- it actually runs in reverse order of declaration within a scope. - Implementing a custom
Dropand also calling.clone()unnecessarily, not realizing Drop only runs once per owned value automatically.
- When a value's owner goes out of scope, Rust calls the
Droptrait'sdropmethod automatically to clean it up. - Values are dropped in the reverse order they were declared within a scope.
- You can implement a custom
Dropfor your own types to run cleanup code, like closing a resource. - You cannot call
.drop()manually -- Rust prevents this to avoid double-free bugs; usestd::mem::dropinstead if needed.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: