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"?
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.