Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 132 ยท Smart Pointers and Memory

Drop and RAII

Master Rust's Drop trait and RAII: when drop runs, drop order for locals, fields and temporaries, mem::drop, mem::forget, scope guards, locks, files and panics.

In many languages you must remember to clean up: close the file, release the lock, free the buffer. Forget once and you have a leak or a deadlock. Garbage-collected languages handle memory but still leave files, sockets and locks to you (finally, using, defer). Rust has a single, uniform answer: tie cleanup to ownership. When a value's owner goes out of scope, Rust runs the value's cleanup code automatically, exactly once, at a predictable moment.

This pattern is called RAII (Resource Acquisition Is Initialization): acquiring a resource happens in a constructor, releasing it happens in the destructor. In Rust the destructor is the Drop trait. You have been relying on it all along: a Vec frees its buffer, a File closes its handle, a MutexGuard unlocks, an Rc decrements its counter, all through Drop. This lesson shows how it works, in what order things happen, how to write your own cleanup, and the few ways to escape it.

The Drop trait

Rust
trait Drop {
    fn drop(&mut self);
}

You implement Drop for a type, and the compiler calls drop when a value of that type is destroyed. You never call it yourself (the compiler forbids it, as you will see below).

Rust A value that announces its destruction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

b is dropped at the closing brace of its block. a and c are dropped when main ends, and c goes first. That brings us to ordering.

Drop order

The rules are simple and deterministic:

  1. Local variables are dropped in reverse order of declaration, like unwinding a stack. A later variable may borrow from an earlier one, so the borrower must go first.
  2. Fields of a struct (and elements of a tuple or array) are dropped in declaration order (first field first), after the struct's own drop has run.
  3. Vec elements are dropped from first to last.
  4. Temporaries are dropped at the end of the statement that created them (with a few special cases, below).
Rust Locals, fields and vectors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

For Pair, the type's own drop runs first ("drop Pair itself ..."), and then the compiler drops first and second in declaration order. You do not write code to drop the fields: the compiler does it for you after your drop returns.

Temporaries, underscores and shadowing

Three details trip people up.

Rust When exactly does a value die

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

  • A temporary such as make("temp") in a statement that never binds it dies at the semicolon.
  • let _ = expr; does not bind anything, so the value is dropped at once. let _name = expr; binds, so it lives to the end of the scope. This difference matters for guards: let _ = mutex.lock(); unlocks immediately and protects nothing!
  • Shadowing a variable does not drop the old value. Both values live until the end of the scope. (Here both Noisy values are dropped when main ends, the newer one first, because locals drop in reverse order.)

Dropping early with drop()

Sometimes you want cleanup before the scope ends: release a lock quickly, close a file before reopening it. std::mem::drop (in the prelude as drop) is just a function that takes its argument by value and does nothing, so the value is dropped as the argument goes out of scope:

Rust
pub fn drop<T>(_x: T) {}

You cannot call the Drop::drop method directly, because it would run twice (once by you, once by the compiler at the end of the scope):

Rust Calling .drop() yourself (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc replies with error E0040, "explicit use of destructor method", and the help "consider using drop function". The fix is drop(r);. Because drop(r) moves r, any later use is a compile error ("borrow of moved value"), so a double drop is impossible.

Rust Early release with drop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Ownership and drops: moves do not duplicate

A value is dropped by whoever owns it last. Moving a value into a function, a struct or a collection transfers the duty:

Rust The new owner drops the value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

a is dropped inside consume. b moves into the Box, and the box drops it at the end of main. At no point is a value dropped twice: the compiler tracks, per variable, whether it still owns something (it uses hidden "drop flags" when this depends on runtime branches).

Writing a real RAII type: scope guards

The strongest use of Drop is a guard whose only job is to run code when a scope ends, whichever way it ends: normal exit, early return, ? or a panic. A simple generic guard takes a closure:

Rust A scope guard that runs a closure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The cleanup line prints for both calls, including the early return Err(...). This is Rust's version of finally/defer, but it is attached to a value, so it composes: guards in different functions nest correctly and run in reverse order.

A very common concrete case is a resource handle. This one tracks open files in a pretend pool and always gives them back:

Rust A pool handle that returns itself on drop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You cannot forget to return a handle; the compiler inserts the call for you. The same design is how MutexGuard unlocks, how RefCell's Ref/RefMut release a borrow, and how BufWriter flushes.

Files and flushing

Real resource types do exactly this. A File closes its descriptor on drop, and a BufWriter flushes its buffer on drop (but errors during that final flush are ignored, so call flush() explicitly when you care):

Rust Files close themselves

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Drop and panics

When a panic unwinds the stack, Rust drops the live locals of each frame on the way up. That is why destructors run even when something fails, and why guards are reliable cleanup. (With panic = "abort" there is no unwinding and no drops.) We can observe it with catch_unwind:

Rust Drops run while a panic unwinds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You see about to fail, then drop inner and drop outer (reverse order) before the final line. One important rule: never panic inside drop if you can avoid it. A panic while already unwinding from another panic aborts the whole process. Make drop infallible: log the error, ignore it, or provide a separate close()/flush() method that returns a Result for callers who care.

mem::forget and ManuallyDrop

Sometimes you want to skip the destructor. std::mem::forget(value) consumes the value without running drop:

Rust mem::forget skips the destructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

forget is a safe function: leaking memory or skipping a destructor is not undefined behaviour, only a bug in most programs. That has a consequence: safe code must never rely on a destructor running for memory safety (the "leakpocalypse" decision). Real uses are narrow: handing ownership of a resource to foreign (C) code, or implementing smart pointers. ManuallyDrop<T> is the finer tool: a wrapper that suppresses automatic drop so you can drop (or not) deliberately, typically inside unsafe implementations.

Drop restrictions worth knowing

  • A type implementing Drop cannot be Copy. Copy types have no ownership duty.
  • You cannot move a field out of a value whose type implements Drop (error E0509), because the destructor would then see a half-empty struct. Use Option::take, mem::replace or mem::take to swap a replacement in.
  • Drop::drop takes &mut self, so it can read and change the value one last time, but cannot move out of it.
  • Generic parameters with Drop bounds are rare. You normally just let T drop when it drops: any T is droppable, whether or not it implements Drop itself.
  • Leaks happen in safe Rust: Rc cycles (see Rc, Arc and Shared Ownership), mem::forget, Box::leak, and threads that never finish.

When to implement Drop

Implement Drop when your type owns a resource that the compiler does not already clean up: a raw handle from an extern "C" library, a temporary file you created, a lock-like flag, a transaction that should roll back unless committed. Don't implement it for plain data; if all fields drop themselves, you don't need to.

A transaction guard shows the "commit or roll back" idiom:

Rust Roll back unless committed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The next lesson, Memory Layout and Sizes, looks at what a value actually occupies in memory.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In what order are the local variables a, b, c (declared in that order) dropped at the end of a scope?

    Locals are dropped in reverse order of declaration, so later variables, which may borrow from earlier ones, go first.
  2. 2. A struct has fields first and second and implements Drop. What happens when it goes out of scope?

    Drop::drop for the struct runs first. Afterwards the compiler drops each field automatically in declaration order.
  3. 3. What is the difference between let _ = make(); and let _guard = make();?

    An underscore pattern does not bind, so the value is dropped at the end of the statement. A named binding, even with a leading underscore, lives to the end of its scope.
  4. 4. Why does r.drop() fail with E0040?

    Rust calls drop automatically at scope end. The std::mem::drop function moves the value away so the compiler knows it is already gone.
  5. 5. Is std::mem::forget unsafe, and what does it do?

    Skipping a destructor cannot cause undefined behaviour by itself, so forget is a safe function. It may leak resources, which is why it is rarely used.

Summary

  • Drop is Rust's destructor: cleanup tied to ownership, run automatically exactly once when the owner goes out of scope. This pattern is RAII.
  • Order: locals in reverse declaration order; struct fields, tuple and array elements in declaration order after the type's own drop; Vec elements first to last; temporaries at the end of their statement.
  • let _ = x drops immediately; let _x = x keeps the value. Shadowing does not drop the old value.
  • You cannot call .drop(); use drop(value) to release early. Moving a value moves the duty to drop it.
  • Guards (MutexGuard, Ref, File, scope guards, transactions) use Drop so cleanup happens on every exit path, including return, ? and panics.
  • Panics unwind and run drops, but a panic inside drop while unwinding aborts the process; keep drop infallible.
  • mem::forget and ManuallyDrop suppress drops. They are safe, but usually leak, so use them rarely.

Next: Memory Layout and Sizes