rustmemory-managementlifetime

Why is referenced variable dropped immediately after the reference is unused?


I don't understand how the following Rust code releases these variables.

struct A(&'static str);

impl A {
    fn as_ref(&self) -> &Self { &self }
}

impl Drop for A {
    fn drop(&mut self) {
        print!("{}", self.0);
    }
}

fn main() {
    let a = A("X");
    let a = A("Y").as_ref();
    print!("Z");
}

Why does this print "YZX"?


Solution

  • Since the expression A("Y") is not bound to a variable, it follows the rules for temporary scopes. For this example, the smallest scope that contains this expression is the statement let a = A("Y").as_ref();. So A("Y") is dropped at the semicolon.

    This means the second a is immediately unusable. This is okay because it is neither used, nor does it have drop behavior.