Why does Rust reject this handle code at compile time?
Question
A teammate ports a C resource helper to Rust, and rustc rejects main.
- Why does the last line fail to compile, and what C bug would happen if it ran?
- In the original code without the last line, when does
Drop::droprun forHandle(7)? - Fix the snippet so
inspectborrows the handle,mainreadsh.0afterward, andHandle(7)closes once at the end ofmain.
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)
- "SINGLE OWNER RULE"
HandleimplementsDrop, so Rust will not copy it. What happens tohwhen you pass it by value intoclose_now? - "WHEN DROP RUNS"
Rust frees a value when its current owner leaves scope. Trace which function owns
Handle(7)afterclose_now(h). - "BORROW WITHOUT MOVING"
Change the parameter to a shared reference
&Handlesomainkeeps 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.
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);
}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.
| style | who frees the resource | after call, can caller read? | failure mode |
|---|---|---|---|
| C raw pointer | Whoever remembers free | Compiles, reads freed RAM | Runtime UB or crash |
Rust move (Handle) | Callee at function exit | Rejected (E0382) | Compile error |
Rust borrow (&Handle) | Caller at scope exit | Yes, safely | None |
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
Copyon a type that implementsDrop. 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); callstd::mem::drop(h)instead, which moveshand drops it. - Thinking ownership adds reference-counting overhead. Plain moves and borrows are checked purely at compile time; only
RcorArccount at runtime. - Cloning heap data just to silence a move error when a borrow
&Tworks.clone()allocates a fresh copy instead of sharing read access.
Follow-up questions
- "How do you release
Handle(7)early beforemainfinishes?" Callstd::mem::drop(h)(in the prelude asdrop(h)). It takeshby value and does nothing inside, soDrop::dropruns immediately and the compiler blocks any later use ofh. - "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, andDropruns once when the lastArcleaves scope. Add aMutex<T>insideArcif 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 ofArcpointers or callingstd::mem::forget(h)skipsDrop, 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 →