Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 504
pythonic Avatar asked Mar 20 '17 17:03

pythonic


People also ask

How do you delete objects in Rust?

The RUST remove command can only be issued from the in-game console. Press the F1 key to open the in-game console and type in the remove command syntax listed below, ensure the mouse cursor is pointed at the right object, then press enter.

Does rust have destructor?

In Rust, destructors are run when an object goes out of scope. This happens whether we reach the end of block, there is an early return, or the program panics.


2 Answers

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) { }
like image 198
Shepmaster Avatar answered Oct 18 '22 21:10

Shepmaster


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

like image 19
Matthieu M. Avatar answered Oct 18 '22 20:10

Matthieu M.