Automatic Resource Management and Memory Safety with Rust's Drop Trait (RAII)
Owner: SnippetBot
Created: 2026-10-31 00:01:12
Size: 2.47 KB
Expires: Never
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::ptr; // Not strictly needed for this simplified example, but common for low-level resources
// A simple struct that "manages" a resource (simulated).
// In real code, this would handle actual heap memory, file handles, network sockets, etc.
struct MyResource {
id: u32,
is_active: bool, // Simulates the state of an allocated/open resource
}
impl MyResource {
fn new(id: u32) -> Self {
println!("[MyResource {}] Allocating/opening resource...", id);
MyResource { id, is_active: true }
}
fn do_something(&self) {
if self.is_active {
println!("[MyResource {}] Performing operation...", self.id);
} else {
println!("[MyResource {}] Error: Resource already inactive/deallocated!", self.id);
}
}
}
// The Drop trait ensures that `drop` is called automatically when the
// MyResource instance goes out of scope. This is Rust's RAII (Resource Acquisition Is Initialization) principle.
impl Drop for MyResource {
fn drop(&mut self) {
if self.is_active {
println!("[MyResource {}] Deallocating/closing resource...", self.id);
// In a real scenario, this is where you'd free memory, close file handles, etc.
self.is_active = false; // Mark as inactive/deallocated
} else {
println!("[MyResource {}] Warning: Resource already marked as inactive before drop!", self.id);
}
}
}
fn main() {
println!("--- Entering main scope ---");
{ // Inner scope 1
let res1 = MyResource::new(1);
res1.do_something();
// res1 automatically drops here, ensuring its resource is cleaned up
} // res1 goes out of scope, Drop::drop() is called
println!("
--- Between scopes ---");
let res2 = MyResource::new(2);
res2.do_something();
// We can manually call `drop` using `std::mem::drop`, but it's usually not needed.
// Once `drop` is called, the resource is considered consumed and cannot be used again.
std::mem::drop(res2); // Explicitly drops res2 early.
// Attempting to use res2 here would be a compile-time error.
// res2.do_something();
println!("
--- After explicit drop ---");
let res3 = MyResource::new(3);
let res4 = MyResource::new(4);
res3.do_something();
res4.do_something();
println!("
--- Exiting main scope ---");
// res3 and res4 will be dropped automatically here in reverse order of creation (stack unwind)
}