How to Use the RAII Pattern in Rust

Implement the Drop trait on a struct to automatically clean up resources when the value goes out of scope.

Use the Drop trait to automatically clean up resources when a value goes out of scope. Define a struct to hold the resource and implement Drop to specify cleanup logic.

struct Resource {
    name: String,
}

impl Drop for Resource {
    fn drop(&mut self) {
        println!("Cleaning up: {}", self.name);
    }
}

fn main() {
    let r = Resource { name: "file.txt".to_string() };
    // Resource is automatically dropped here
}