Skip to content

Q027. What is the difference between Drop::drop and std::mem::drop?

Short Answer

Drop::drop(&mut self) is the destructor hook Rust calls automatically and cannot be invoked directly in safe code. std::mem::drop(value) is an ordinary generic function that takes ownership of a value; its empty body lets the parameter be destroyed before returning. For a Copy argument, only the copied argument is dropped and the original remains usable.

Deep Dive

Calling Drop::drop directly would run cleanup while leaving the original variable accessible as if it still contained a valid value. Rust rejects that with E0040, preventing later use or automatic destruction from causing use-after-drop or double cleanup.

std::mem::drop is effectively:

rust
pub fn drop<T>(_value: T) {}

Passing a non-Copy value moves it into the function. The parameter reaches its drop point before the function returns, so the caller cannot use the original afterward. This is useful for releasing guards, borrows, files, or large buffers before their surrounding scope ends.

Low-level unsafe code can use ptr::drop_in_place when a value must be destroyed without moving it.

Internal Model

Drop::drop is one step inside a type's complete destructor. After it returns, generated drop glue recursively destroys the fields. It does not itself deallocate storage containing self.

std::mem::drop has no compiler magic beyond normal move and parameter destruction semantics, so it is usually inlined away after scheduling the required cleanup.

Example

rust
use std::cell::RefCell;

fn main() {
    let value = RefCell::new(1);

    let mut guard = value.borrow_mut();
    *guard += 1;
    drop(guard);

    let shared = value.borrow();
    println!("{shared}");
}

Common Mistakes

  • Calling value.drop() or Drop::drop(&mut value) explicitly.
  • Thinking std::mem::drop deallocates raw memory directly.
  • Expecting drop(copy_value) to make the original Copy variable unavailable.

Follow-ups

  • When is ptr::drop_in_place required?
  • Why does Drop::drop receive &mut self?
  • How can explicit drop reduce lock or borrow duration?

References

  • Rust Reference
  • Rust Standard Library