Special case at temporary drop order

Hey folks,

this topic led my to this part of the docs where you can read:

Temporaries that are created in the final expression of a function body are dropped after any named variables bound in the function body, as there is no smaller enclosing temporary scope.

I don't quite understand the reasoning behind this behavior ((...) as there is no smaller enclosing temporary scope) and would be very grateful if someone could explain it to me. :slight_smile:

Regards
keks

The doc link is a bit outdated because the wording is fixed recently if you really follow the replies in that post. Latest doc: https://github.com/rust-lang/reference/blob/master/src/destructors.md#temporary-scopes

New: Temporaries that are created in the final expression of a function body are dropped after any named variables bound in the function body. Their drop scope is the entire function, as there is no smaller enclosing temporary scope.

The sentence just describes an intuitive case that a return value from a function will drop (if it needs to drop) after all the named local variables because there is no enclosing drop scope for that temporary in that function.

struct PrintOnDrop(&'static str);
impl Drop for PrintOnDrop {
    fn drop(&mut self) {
        println!("drop({})", self.0);
    }
}
fn f(s: &'static str) -> PrintOnDrop {
    let x = PrintOnDrop(s);
    PrintOnDrop("f") // This drops outside the current function body
}
fn main() {
    let var1 = f("var 1");
}
// drop(var 1)
// drop(f)

But the example code in Reference plays a trick in main by using wildcard pattern (_) in match to show the out-of-current-function-body drop behavior without the redundant f: Rust Playground

2 Likes

I see! :slight_smile: Thank you very much!:medal_sports::+1: