How to Handle Resource Cleanup in Rust (RAII)

Rust uses the Drop trait to automatically clean up resources when variables go out of scope, ensuring safe memory management without manual intervention.

Rust handles resource cleanup automatically through the Drop trait, which runs code when a value goes out of scope, eliminating the need for manual cleanup. This RAII (Resource Acquisition Is Initialization) pattern ensures resources like file handles or mutex locks are released immediately when they are no longer needed, preventing leaks and deadlocks.

use std::thread;
use std::sync::Mutex;

fn main() {
    let counter = Mutex::new(0);
    let mut handles = vec![];

    for _ in 0..10 {
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
            // MutexGuard drops here, automatically unlocking the mutex
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}