skip to content

In Rust, in what order are a function's local variables and a struct's fields dropped, and when does the struct's own Drop::drop run?

level: middleimportance: should knowfreq 50%

answer

  1. locals and fields go opposite ways
  2. last declared local goes first
  3. fields follow the struct definition
  4. outer drop sees a whole value

basics

~20 s

Locals in one scope drop in reverse declaration order; a struct's fields drop in declaration order. A struct's own Drop::drop runs first, while every field is still intact, and the fields are destroyed after it returns.

solid answer

~40 s

When a scope ends, its variables are dropped in **reverse order of declaration**, so a connection declared after its pool is returned before the pool goes away. A value's destructor runs `Drop::drop` first, if the type implements it, with every field still alive, then destroys the fields in the order the **struct definition** declares them; the order in a struct literal does not matter. Tuples drop in order, arrays first element to last. Both orders are guaranteed by the language, so you can rely on them: put a field that must outlive its siblings last, and declare a local that others depend on first.

code

rust · 27 lines
rust
struct Noisy(&'static str);

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

#[allow(dead_code)]
struct TempFile {
    handle: Noisy,
    path: Noisy,
}

impl Drop for TempFile {
    fn drop(&mut self) {
        println!("TempFile::drop removes the file");
    }
}

fn main() {
    let _pool = Noisy("pool");
    let _conn = Noisy("conn");
    // The literal lists `path` first; declaration order still decides.
    let _tmp = TempFile { path: Noisy("path"), handle: Noisy("handle") };
    println!("end of main");
}

go deeper

for a junior

Remember the two directions: locals in a block go last-declared-first, fields of a struct go first-declared-first.

for a middle

Explain the two steps of a destructor: the type's own Drop::drop runs with all fields intact, then the drop glue destroys fields in declaration order, and literal order is irrelevant.

for a senior

Use the guarantee deliberately: order fields and locals so dependants go first, and spot the Drop::drop that assumes a field is already closed, fixing it with an Option field.

for a principal

Prefer declaration order over ManuallyDrop for controlling teardown, and document a load-bearing field order in the struct so a later refactor that reorders fields does not silently change it.

## Two rules that point in opposite directions Rust guarantees the order in which values are destroyed, and the two most common cases go in opposite directions: - **Local variables** in one scope are dropped in **reverse order of declaration**: the last `let` is destroyed first. - **Fields of a struct** are dropped in **declaration order**: the first field written in the `struct` definition is destroyed first. The Rust Reference states both, and the documentation of the `Drop` trait calls the field order "guaranteed by the language". The rest of this answer is what each rule means for a resource-owning type, such as a temporary-file wrapper or a pool guard. ## Locals: last in, first out Each block is a **drop scope**. When control leaves it, by reaching the closing brace, a `return`, a `?` or a `break`, the variables declared in it are dropped from the most recent back to the first. **Temporaries** in one scope are likewise dropped in reverse order of creation, and when several scopes are left at once, inner scopes are emptied before outer ones. Function parameters live in the scope of the whole function, so they are dropped after every local in the body. This ordering matches dependencies naturally. You create the pool before you check out a connection, so the connection is dropped, and handed back, while the pool still exists. Where a later value **borrows** an earlier one, the borrow checker enforces this for you: a value cannot be destroyed while something that borrows it is still alive. ## Fields: the destructor first, then the fields in declaration order A value's destructor has two steps: 1. If its type implements `Drop`, `Drop::drop(&mut self)` runs. At this moment **every field is still alive**, so the method can read them, flush a buffer, or remove the file at `self.path`. 2. The compiler's **drop glue** then destroys each field in the order the struct declares it, recursing into each field's own destructor. Other compound types follow the same spirit: | Value | Order its parts are dropped | |---|---| | struct fields | declaration order in the `struct` definition | | tuple elements | first to last | | array or owned slice elements | first to last | | active enum variant's fields | declaration order | | variables captured by a `move` closure | unspecified | Two consequences surprise people. First, the order of fields in a **struct literal** is irrelevant; `TempFile { path, handle }` still drops `handle` first if `handle` is declared first. Second, a field's resources are not released until **after** the outer `Drop::drop` returns, so code inside `drop` cannot assume a field has already been cleaned up. ## Designing with the guarantee Because the order is guaranteed, the idiomatic way to control it is to **arrange declarations**, not to add machinery: - put the field that must be destroyed last, such as a shared context the other fields use, at the **end** of the struct; - declare a local that others depend on **before** them; - when `Drop::drop` itself needs a field gone first (for instance, a file handle closed before the file is removed), store that field as an `Option` and drop its contents explicitly inside `drop`. The standard library's own documentation for `ManuallyDrop` recommends reordering declarations first, and suppressing drops with `ManuallyDrop` only when reordering cannot express what you need, because that path requires unsafe code. ## A worked trace For a function that declares `_pool`, then `_conn`, then `_tmp: TempFile { handle, path }`, the end of the function runs, in order: `TempFile::drop` on `_tmp`, then `_tmp.handle`, then `_tmp.path`, then `_conn`, then `_pool`. The local rule decides that `_tmp` goes first; the field rule decides the order inside it. ## Where people go wrong - Assuming fields mirror locals and drop in reverse. They do not; only variables in a scope are reversed. - Writing a `Drop::drop` that expects a field's own cleanup to have happened already. It has not; fields are destroyed after `drop` returns. - Reordering struct fields in a refactor for readability and silently changing teardown order. If the order is load-bearing, say so in a comment on the struct. - Believing the order is unspecified and adding `ManuallyDrop` or explicit `drop` calls "to be safe", when the language already guarantees it.

  • A `TempFile` holds `file: File` and `path: PathBuf`, and its `Drop::drop` calls `std::fs::remove_file(&self.path)`. Is the file still open at that moment?
    Yes. Fields are destroyed only after `Drop::drop` returns, so the `File` is still open when `remove_file` runs, and the `remove_file` documentation notes that, depending on platform, other open file descriptors may prevent immediate removal. Store the handle as `Option<File>` and call `drop(self.file.take())` before removing the path.
  • In what order are function parameters dropped relative to the function's locals?
    Parameters belong to the scope of the whole function, so they are dropped after every local in the body. Among parameters that bind patterns, each pattern's bindings are dropped before the parameter value they came from.
  • If a struct does not implement `Drop`, are its fields still dropped in order?
    Yes. Without an `impl Drop` there is simply no first step; the drop glue still destroys each field in declaration order, running each field's own destructor.

  • Struct fields are dropped in reverse declaration order, like locals.
  • Fields are destroyed before the struct's own Drop::drop runs.
  • The order of fields in a struct literal decides their drop order.
  • Drop order is unspecified, so code must never depend on it.
  • Locals are dropped in the order they were declared.