Drop Order Of Fields And Locals
Struct fields drop in declaration order while locals drop in reverse, so paired resources release in a predictable, observable sequence.
Code
// 用 Drop 打印名字来观察释放顺序
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("dropped {}", self.0);
}
}
// 字段释放顺序 = 声明顺序:先 first,后 second
struct DropOrderJob {
first: Guard,
second: Guard,
}
fn main() {
{
let job = DropOrderJob {
first: Guard("job.first"),
second: Guard("job.second"),
};
println!("job built");
drop(job); // 显式 drop 也按字段声明顺序执行
}
println!("---");
// 局部变量按声明逆序释放:inner 先于 outer
let outer = Guard("outer");
let inner = Guard("inner");
println!("locals built");
} // 这里依次打印 dropped inner、dropped outerWhat the code does
Drop Order Of Fields And Locals reduces to the functions drop and main.
Applying it
The main signature reads fn drop(&mut self)
The demo output is labeled (dropped, job built, ---), so every printed line maps back to its originating operation.
Launch the file; main takes over and steps through drop.
Statements that matter
impl Drop for Guard {
fn drop(&mut self) {
println!("dropped {}", self.0);
}
}
Interactive Tools for This Topic
FAQ
- What does Drop Order Of Fields And Locals print when run?
- The script runs standalone; its 4 labeled outputs include `dropped`, `job built`, `---`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.