Special case at temporary drop order

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