← All notes

Run cleanup when a Rust value goes out of scope with Drop

Answer: The Drop trait lets you customize cleanup when a value is about to go out of scope. You can implement Drop on any type, and use that code to release resources like files or network connections.

Destructors

When a value is no longer needed, Rust will run a destructor on that value. That destructor calls Drop::drop if the type implements the trait, then drop glue recursively calls the destructors of all the fields of this value. Because field destructors run automatically, you don't have to implement Drop in most cases. Implement it for types which directly manage a resource.

Early cleanup

Occasionally you might want to clean up a value early. Call the std::mem::drop function provided by the standard library to force a value to be dropped. That function is different from the drop method in the Drop trait.

| Drop | destructor | |---|---| | Drop trait | Customize what happens when a value goes out of scope | | Drop::drop | Custom code within the destructor | | drop glue | Recursively calls the destructors of all contained fields | | std::mem::drop | Function that force-drops a value early |

See

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: The Rust Programming Language, Running Code on Cleanup with the Drop Trait; Rust standard library, Trait Drop. MIT OR Apache-2.0; MIT OR Apache-2.0. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: The Rust Programming Language, Running Code on Cleanup with the Drop Trait; Rust standard library, Trait Drop. MIT OR Apache-2.0; MIT OR Apache-2.0.

Cite this

Permanent ID: iil:note:49j2ehwd

iinventedlight. 2026. "Run cleanup when a Rust value goes out of scope with Drop." iinventedlight Library, iil:note:49j2ehwd, version of 2026-11-19. https://iinventedlight.com/library/notes/rust-drop/. License: CC-BY-4.0.

@misc{iil_note_49j2ehwd,
  author = {{iinventedlight}},
  title = {{Run cleanup when a Rust value goes out of scope with Drop}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-19},
  url = {https://iinventedlight.com/library/notes/rust-drop/},
  note = {Permanent ID iil:note:49j2ehwd. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/rust-drop.md.