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
}