Reassignment Drops The Old Value

Assigning a new value into a mut binding drops the previous one on the spot, verified with a Drop impl that prints each release.

RustData Integrity

Code

rustsnippet
27 lines
struct Tracked {
    label: &'static str,
}

impl Drop for Tracked {
    fn drop(&mut self) {
        println!("drop: {}", self.label);
    }
}

fn main() {
    let mut slot = Tracked { label: "first" };
    println!("holding: {}", slot.label);

    // reassignment drops the previous value right here, not at scope end
    slot = Tracked { label: "second" };
    println!("holding: {}", slot.label);

    // explicit drop releases it early
    drop(slot);
    println!("slot released");

    // shadowing instead keeps both values alive until the scope ends
    let a = Tracked { label: "shadow-a" };
    let a = Tracked { label: "shadow-b" };
    println!("shadowed: {}", a.label);
}

How the snippet works

The moving parts are the functions drop and main.

Applying it

The entry-point signature is fn drop(&mut self)

The demo output is labeled (drop:, holding:, slot released); each label names the call that printed it.

The sequence drop lives in main; running the file triggers it.

Statements that matter

impl Drop for Tracked {
    fn drop(&mut self) {
        println!("drop: {}", self.label);
    }
}

Interactive Tools for This Topic

FAQ

What does Reassignment Drops The Old Value print when run?
The script runs standalone; its 4 labeled outputs include `drop:`, `holding:`, `slot released`.