For example, code:
#[derive(Debug)]
struct A(i32);
impl A {
fn new(a: i32) -> A {
println!("A::new({})", a);
A(a)
}
}
impl Drop for A {
fn drop(&mut self) {
println!("A::drop({})", self.0);
}
}
fn main() {
let x = A::new(0);
let y = A::new(1);
println!("{:?}", y);
println!("{:?}", x);
}
This code gives output:
A::new(0)
A::new(1)
A(1)
A(0)
A::drop(1)
A::drop(0)
Why Rust does not drop the variable 'y' earlier, as showed on output below?
A::new(0)
A::new(1)
A(1)
A::drop(1)
A(0)
A::drop(0)
What is reason of this behavior of Rust's compiler?