Rust Reference ยท Core Traits
The Drop trait
Reference for the Rust Drop trait: run cleanup code when a value goes out of scope, drop order for locals and fields, mem::drop, mem::forget and the rules.
Drop lets a type run code at the moment a value is destroyed: closing a file, releasing a lock, flushing a buffer, logging. The compiler inserts the call when the owner goes out of scope, is overwritten, or is passed to drop(). This is Rust's RAII model, and it is how File, MutexGuard, Box and Vec clean up after themselves.
You never call value.drop() yourself; the compiler rejects it. To end a value's life early, call std::mem::drop(value) (it is in the prelude as drop), which simply takes ownership and lets the value go out of scope.
impl Drop for Guard { fn drop(&mut self) { println!("cleanup"); } }
Try it
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.
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.
Syntax
pub trait Drop { fn drop(&mut self); }
| Name | Description |
|---|---|
&mut self |
The value being destroyed. Its fields are still valid inside drop, and are dropped automatically afterwards. |
Returns: nothing. There is no way to report an error from drop.
Usage notes
- Order for locals: variables drop in reverse order of declaration (
bbeforea). Temporaries drop at the end of the statement that created them. - Order for fields: a struct's own
dropruns first, then its fields drop in declaration order. Tuple and array elements drop in order too.Vecdrops its elements front to back. - Assignment drops the old value at the moment of assignment.
let _ = value;does not bind and drops immediately, whilelet _x = value;keeps it until scope end. - Moved-out values are not dropped twice. A value moved into a function or another variable is dropped by its new owner, not the old one.
- Panics:
dropruns during unwinding, which is how locks are released. A panic insidedropwhile already unwinding aborts the process, so keepdroppanic-free. Copytypes cannot implementDrop. Also aDroptype cannot be destructured by moving fields out of it.- Leaking is safe.
mem::forget, reference cycles inRcandBox::leakskipdropwithout violating memory safety, so never rely onDropfor soundness of unsafe code (only for cleanup). - Cannot call it:
value.drop()is error E0040. Usedrop(value). - Process exit and
statics: statics never drop, andstd::process::exitdoes not run destructors for live locals. - Dropping a reference: dropping a reference does nothing (clippy warns); drop the owner instead.
- Prefer scopes or explicit methods for fallible cleanup.
Fileflushes on drop but ignores errors; callflush()orsync_all()yourself if you need to see them.
Related
Copy,DerefandDerefMut,Clone- Lessons: Drop and RAII, Ownership, Rc and Arc