capypad
0 day streak
rust / intermediate
Snippet

Implementing the Drop Trait for RAII Cleanup

The Drop trait enables Resource Acquisition Is Initialization (RAII) patterns in Rust. When a value goes out of scope, drop() is automatically called, allowing you to release resources like files, network connections, or memory. This is Rust's primary mechanism for deterministic cleanup.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
struct FileWrapper {
filename: String,
}
 
impl Drop for FileWrapper {
fn drop(&mut self) {
println!("Cleaning up file: {}", self.filename);
}
}
 
struct DatabaseConnection {
conn: FileWrapper,
connected: bool,
}
 
impl Drop for DatabaseConnection {
fn drop(&mut self) {
if self.connected {
println!("Closing database connection for: {}", self.conn.filename);
}
}
}
 
fn main() {
let db = DatabaseConnection {
conn: FileWrapper { filename: String::from("data.db") },
connected: true,
};
println!("Database in use...");
}
Breakdown
1
impl Drop for FileWrapper
Implements Drop for automatic cleanup notification
2
fn drop(&mut self)
Called automatically when FileWrapper goes out of scope
3
struct DatabaseConnection
Composite struct containing FileWrapper
4
impl Drop for DatabaseConnection
Drops are called in reverse declaration order
5
if self.connected { ... }
Conditional cleanup based on connection state