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) }