download

Why does Rust reject this handle code at compile time?

Systems~10 minReviewed 2 Dec 2026Free · No sign-in

Question

A teammate ports a C resource helper to Rust, and rustc rejects main.

  1. Why does the last line fail to compile, and what C bug would happen if it ran?
  2. In the original code without the last line, when does Drop::drop run for Handle(7)?
  3. Fix the snippet so inspect borrows the handle, main reads h.0 afterward, and Handle(7) closes once at the end of main.
"CODE · RUST"
struct Handle(u32);
impl Drop for Handle {
    fn drop(&mut self) { println!("close {}", self.0); }
}

fn close_now(h: Handle) {
    println!("transfer {}", h.0);
}

fn main() {
    let h = Handle(7);
    close_now(h);
    println!("still using {}", h.0);
}
Show hints (3)
  1. "SINGLE OWNER RULE"

    Handle implements Drop, so Rust will not copy it. What happens to h when you pass it by value into close_now?

  2. "WHEN DROP RUNS"

    Rust frees a value when its current owner leaves scope. Trace which function owns Handle(7) after close_now(h).

  3. "BORROW WITHOUT MOVING"

    Change the parameter to a shared reference &Handle so main keeps ownership.

Show checked explanation

Passing h by value moves ownership into close_now, which drops Handle(7) when it returns. Reading h.0 afterward fails at compile time (E0382), blocking a C use-after-free and double-free. Pass &Handle instead so inspect borrows it and main closes Handle(7) once at exit.

"SOLUTION · RUST"
struct Handle(u32);
impl Drop for Handle {
    fn drop(&mut self) {
        println!("close {}", self.0);
    }
}

fn inspect(h: &Handle) {
    println!("borrow {}", h.0);
}

fn main() {
    let h = Handle(7);
    inspect(&h);
    println!("still using {}", h.0);
}
"OUTPUT"
borrow 7
still using 7
close 7

Compiled both the rejected starter (E0382) and fixed RAII solution, plus LIFO drop checks, with rustc 1.94.1 on Windows x64. Checked by an editor other than the author.

Walkthrough

In C, passing a heap pointer Handle *h copies the raw address. If close_now(h) calls free(h), the caller still holds that pointer. Reading h->id becomes a use-after-free, and freeing it again in main causes a double-free.

Rust ties cleanup to a single owner (RAII via Drop). Because Handle does not implement Copy, calling close_now(h) moves ownership into close_now. When close_now returns, Rust inserts Drop::drop(&mut h) automatically and prints close 7. The compiler marks h in main as moved and refuses to compile h.0 (E0382), with zero runtime tracking cost.

stylewho frees the resourceafter call, can caller read?failure mode
C raw pointerWhoever remembers freeCompiles, reads freed RAMRuntime UB or crash
Rust move (Handle)Callee at function exitRejected (E0382)Compile error
Rust borrow (&Handle)Caller at scope exitYes, safelyNone

Changing the parameter to h: &Handle lends read access without moving ownership. inspect(&h) prints borrow 7 and returns without dropping h. Then main prints still using 7, reaches its closing brace, and runs drop exactly once to print close 7.

When a scope holds several owned values, Rust drops them in reverse declaration order (LIFO), so later handles that borrow from earlier ones close first.

Common mistakes

  • Trying to derive Copy on a type that implements Drop. Rust rejects this because copying an owning handle would trigger two drops on one resource.
  • Calling h.drop() directly to release early. Rust forbids explicit destructor calls (E0040); call std::mem::drop(h) instead, which moves h and drops it.
  • Thinking ownership adds reference-counting overhead. Plain moves and borrows are checked purely at compile time; only Rc or Arc count at runtime.
  • Cloning heap data just to silence a move error when a borrow &T works. clone() allocates a fresh copy instead of sharing read access.

Follow-up questions

  • "How do you release Handle(7) early before main finishes?" Call std::mem::drop(h) (in the prelude as drop(h)). It takes h by value and does nothing inside, so Drop::drop runs immediately and the compiler blocks any later use of h.
  • "What if two threads genuinely need to share ownership of a resource?" Wrap it in Arc<T> (atomic reference count). Each clone increments the count, and Drop runs once when the last Arc leaves scope. Add a Mutex<T> inside Arc if threads also mutate it.
  • "Can Rust still leak a resource even with Drop?" Yes. Safe Rust prevents use-after-free and double-free, not all leaks. A cycle of Arc pointers or calling std::mem::forget(h) skips Drop, because leaking memory is memory-safe.

What a strong answer covers

Connects move semantics to C use-after-free and double-free bugs, traces the exact Drop point, replaces the move with &Handle, and notes zero runtime overhead.

Open in interactive practice deck →

Original OfferVibe question. The Rust Book: What Is Ownership? · std::ops::Drop.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.