pythonic
pythonic

Reputation: 21635

Is it possible in Rust to delete an object before the end of scope?

From what I understand, the compiler automatically generates code to call the destructor to delete an object when it's no longer needed, at the end of scope.

In some situations, it is beneficial to delete an object as soon as it's no longer needed, instead of waiting for it to go out of scope. Is it possible to call the destructor of an object explicitly in Rust?

Upvotes: 37

Views: 23954

Answers (2)

Shepmaster
Shepmaster

Reputation: 431489

Is it possible in Rust to delete an object before the end of scope?

Yes.

Is it possible to call the destructor of an object explicitly in Rust?

No.

To clarify, you can use std::mem::drop to transfer ownership of a variable, which causes it to go out of scope:

struct Noisy;

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("Dropping Noisy!");
    }
}

fn main() {
    let a = Noisy;
    let b = Noisy;

    println!("1");

    drop(b);

    println!("2");
}
1
Dropping Noisy!
2
Dropping Noisy!

However, you are forbidden from calling the destructor (the implementation of the Drop trait) yourself. Doing so would lead to double free situations as the compiler will still insert the automatic call to the the Drop trait.


Amusing side note — the implementation of drop is quite elegant:

pub fn drop<T>(_x: T) { }

Upvotes: 56

Matthieu M.
Matthieu M.

Reputation: 299999

The official answer is to call mem::drop:

fn do_the_thing() {
    let s = "Hello, World".to_string();
    println!("{}", s);

    drop(s);

    println!("{}", 3);
}

However, note that mem::drop is nothing special. Here is the definition in full:

pub fn drop<T>(_x: T) { }

That's all.

Any function taking ownership of a parameter will cause this parameter to be dropped at the end of said function. From the point of view of the caller, it's an early drop :)

Upvotes: 26

Related Questions