Rust
Beginner
1 min read
Scope, Drop, and the Drop Trait
Example
struct Connection {
name: String,
}
impl Connection {
fn new(name: &str) -> Self {
println!("[{name}] opened");
Connection { name: name.to_string() }
}
}
impl Drop for Connection {
fn drop(&mut self) {
println!("[{}] closed", self.name);
}
}
fn main() {
let _outer = Connection::new("outer");
{
let _inner = Connection::new("inner");
println!("inside inner scope");
} // _inner is dropped here → "[inner] closed"
println!("after inner scope");
let early = Connection::new("early");
println!("about to drop 'early' explicitly");
drop(early); // std::mem::drop — drops before end of scope
println!("'early' has been dropped");
// _outer is dropped here at the end of main → "[outer] closed"
}
// Expected output:
// [outer] opened
// [inner] opened
// inside inner scope
// [inner] closed
// after inner scope
// [early] opened
// about to drop 'early' explicitly
// [early] closed
// 'early' has been dropped
// [outer] closed