In the Rust book an example is provided in chapter 15 section 3 to show when Rust runs the drop function on the variables c and d.
struct CustomSmartPointer {
data: String,
}
impl Drop for CustomSmartPointer {
fn drop(&mut self) {
println!("Dropping CustomSmartPointer with data `{}`!", self.data);
}
}
fn main() {
let c = CustomSmartPointer {
data: String::from("my stuff"),
};
let d = CustomSmartPointer {
data: String::from("other stuff"),
};
println!("CustomSmartPointers created.");
}
and the output is:
CustomSmartPointers created.
Dropping CustomSmartPointer with data `other stuff`!
Dropping CustomSmartPointer with data `my stuff`!
My question is why does the rust compiler drop the variables in this order? Given that the variables are not used or referenced shouldn’t they be dropped right after they are declared, and be dropped in the order they were declared?
I have also tried the same code with another declared variable.
//snip
let e = CustomSmartPointer {
data: String::from("more stuff"),
};
and the output stays reversed
CustomSmartPointers created.
Dropping CustomSmartPointer with data `more stuff`!
Dropping CustomSmartPointer with data `other stuff`!
Dropping CustomSmartPointer with data `my stuff`!
Although the way variables are dropped reminds of how data is pushed and popped off a stack, but that should be a red herring.
Anthony Ruiz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.