What Is the Drop Trait and How to Customize Cleanup in Rust

The Drop trait in Rust allows you to define custom cleanup code that executes automatically when a value goes out of scope.

The Drop trait lets you define custom cleanup code that runs automatically when a value goes out of scope. Implement the drop method on your type to execute logic like closing files or releasing network connections just before the memory is freed.

use std::fmt;

struct CustomSmartPointer {
    id: i32,
}

impl Drop for CustomSmartPointer {
    fn drop(&mut self) {
        println!("Dropping CustomSmartPointer with id `{}`", self.id);
    }
}

fn main() {
    let c = CustomSmartPointer { id: 1 };
    println!("CustomSmartPointer created.");
} // Drop runs here automatically