Skip to content
tezvyn:
Menu

Rust's `Drop` Trait: Automatic Resource Cleanup

Source: doc.rust-lang.orgMediumHow cards are made

Rust's Drop trait provides automatic, deterministic cleanup, like a destructor. It's used to release external resources like file handles or network sockets when a value goes out of scope. The key footgun: you cannot implement Drop on a Copy type.

Why it exists

Languages need a way to manage resources like memory, file handles, or network connections. Instead of relying on a garbage collector or manual cleanup calls, Rust uses the ownership system combined with the Drop trait. This enables a pattern called RAII (Resource Acquisition Is Initialization), where resource cleanup is tied to an object's lifetime, making leaks much harder.

The mental model

Think of a type with a Drop implementation as a self-cleaning tool. When you're finished using it and it goes out of scope, it automatically cleans itself up and returns its resources. You don't have to remember to call file.close() because the File type's Drop implementation handles it for you the moment the variable is no longer needed.

How it works

To define custom cleanup logic, you implement the drop(&mut self) method for your type. When a value of that type goes out of scope, Rust automatically calls your drop method. Afterwards, it recursively drops each of the struct's fields. The drop order is guaranteed: for local variables, it's Last-In, First-Out (reverse order of declaration). For struct fields, it's the same order they are declared in the struct definition.

When to use it

Implement Drop when your type directly manages a resource that Rust doesn't know how to clean up on its own. This is common for types that wrap raw pointers from a C library, or manage low-level OS resources like file descriptors or sockets. Most of the time, you don't need it, as composing standard library types like Vec or Box is enough; the compiler will generate the necessary drop logic for you.

When not to use it

You cannot implement Drop on a type that also implements Copy. The two are mutually exclusive because if a type can be trivially bit-copied, it becomes ambiguous which copy is responsible for cleaning up the resource. You also cannot call the drop method directly for safety reasons; if you need to force a value to be dropped early, use the global function std::mem::drop().

One canonical example

The standard library's std::fs::File is the classic example. When you open a file, a File struct is returned which holds onto the operating system's file handle. The File struct implements Drop, and its drop method ensures the underlying file is closed. This happens automatically when the File variable goes out of scope, preventing resource leaks even in the case of panics.

Interview question

What is the primary reason Rust prevents implementing the Drop trait for types that also implement Copy?

  • a.It would lead to ambiguity about which copy is responsible for cleaning up the resource.Correct
  • b.Drop implementations would introduce performance overhead that contradicts the nature of Copy types.
  • c.Copy types are always stored on the stack, making Drop unnecessary.
  • d.Copy types are designed to be immutable, and Drop requires mutable access.
Why?

The card states that Drop and Copy are mutually exclusive because "if a type can be trivially bit-copied, it becomes ambiguous which copy is responsible for cleaning up the resource." This prevents issues like double-freeing. While Copy types are often simple and cheap (making option B tempting), the fundamental reason for the restriction is the ambiguity of resource ownership and cleanup, not just performance.

Just read this? Test yourself on what you have been reading.

Read the original → doc.rust-lang.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on rust — each one lists the topics its interview covers.

See open roles