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

11,841

Solution 1

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) { }

Solution 2

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 :)

Share:
11,841

Related videos on Youtube

pythonic
Author by

pythonic

Updated on September 14, 2022

Comments

  • pythonic
    pythonic over 1 year

    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?

  • Shepmaster
    Shepmaster about 7 years
    drop is in the prelude; no need to qualify it.
  • Francis Gagné
    Francis Gagné about 7 years
  • Nawaz
    Nawaz over 5 years
    What is destructor in Rust? Did you mean drop?
  • Shepmaster
    Shepmaster over 5 years
    @Nawaz there's no material difference. drop is just the name of Rust's destructor function.