Rustlers Atom 2.5: Scope, Drop and distruction determinism

Rust uses Resource Acquisition Is Initialization (RAII). This means the life of a resource (memory, file handle, network socket) is tied directly to the life of the variable bound to it.

In garbage-collected languages, objects are cleaned up "eventually." In Rust, cleanup is deterministic. It happens exactly when the owner goes out of scope. This is handled by the Drop trait. When a value’s scope ends, Rust automatically calls its drop function.

struct CustomSmartPointer {
    data: String,
}

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

fn main() {
    let c = CustomSmartPointer { data: String::from("my stuff") };
    let d = CustomSmartPointer { data: String::from("other stuff") };
    println!("CustomSmartPointers created.");
} // d goes out of scope, then c goes out of scope.

Notice the order, is a Last-In, First-Out (LIFO) queue. Variables declared later are dropped first. This is crucial because later variables might depend on earlier ones.

Manual Drop

You cannot call the .drop() method manually. Rust forbids it to prevent "double free" errors (trying to clean up memory that Rust is already scheduled to clean up). If you need to force a value to be dropped early (for example, to release a lock or close a file immediately), use the standard library function std::mem::drop.

use std::mem;

fn main() {
    let v = vec![1, 2, 3];

    // Explicitly drop v before the end of the scope
    mem::drop(v); 

    // println!("{:?}", v); // ❌ compile error: value used after move
    println!("v is already gone.");
}

You'll only receive email when they publish something new.

More from GSLF
All posts