Why is drop called before end of scope?


#1

Trying to get a printout at the end of the scope for a variable but the drop function is called when there i no more use of the variable

struct DropGuard(());

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

fn main() {
    {
        let _ = DropGuard(());
        println!("from scope");
    }
    println!("from outside of scope");
}

this give the printout:
from drop
from scope
from outside of scope

but I want:
from scope
from drop
from outside of scope

is this possible?


#2

With let _ = you’re not actually creating a binding for the DropGuard value, so the value only lives until the end of the expression. To create a binding, you need to give it a name, for example:

fn main() {
    {
        let _guard = DropGuard(());
        println!("from scope");
    }
    println!("from outside of scope");
}

#3

that did it, thanks for the help have been trying to figure it out all day


#4

Implementing the following macro I had to ensure a data-element is put onto stack of main-function and not removed until leaving the scope. The asm-expression was necessary to prevent it is optimized-out creating a release-build.

Rust (nightly) supports also the “#[used]” annotation to prevent the data is removed by optimizer
https://doc.rust-lang.org/unstable-book/language-features/used.html