In Rust, why does calling `conn.drop()` on a pooled connection guard fail to compile, and how do you release it early instead?
answer
- a destructor must run exactly once
- Drop::drop only borrows self
- explicit destructor call error code
- prelude function that takes ownership
basics
~10 srustc rejects conn.drop() with E0040: Drop::drop only borrows the value, so it would stay usable and be dropped again at scope end. Call std::mem::drop(conn) instead; it takes ownership and runs the destructor once, immediately.
solid answer
~40 s`Drop::drop` takes `&mut self`, so calling it by hand would leave `conn` alive and usable, and the compiler would still run the destructor when the scope ends: a double release of the same connection. rustc therefore refuses any explicit call, method syntax or `Drop::drop(&mut conn)`, with E0040, "explicit use of destructor method". To give the connection back early, move the guard into `std::mem::drop` (in the prelude as `drop`). Its body is empty; taking the guard by value ends its life inside the call, so the destructor runs exactly once, now, and any later use of `conn` is E0382. An inner block `{ ... }` around the guard's use does the same job.
code
rust · 21 linesstruct PooledConn {
id: u32,
}
impl Drop for PooledConn {
fn drop(&mut self) {
println!("conn {} back in pool", self.id);
}
}
fn checkout(id: u32) -> PooledConn {
println!("conn {id} checked out");
PooledConn { id }
}
fn main() {
let conn = checkout(1);
println!("query on conn {}", conn.id);
drop(conn); // std::mem::drop, in the prelude: the pool gets it back now
println!("long report rendering, no connection held");
}go deeper
Recall that the compiler calls the destructor for you at scope end, that conn.drop() is error E0040, and that drop(conn) from the prelude is the way to release a guard early.
Explain why: Drop::drop takes &mut self, so an explicit call would leave the value alive and dropped twice; std::mem::drop takes ownership, so the move ends its life inside the call.
Show where early release pays off in a service, such as returning a pooled connection before slow rendering, and spot drop(&conn) and drop on Copy values in review by their lints.
Treat explicit drop calls as signals: a function needing several is usually doing too much under one guard, and splitting it into scoped helpers makes release points visible without manual calls.
## What `Drop` is and when it runs In Rust, a **destructor** is the code that runs when a value's owner goes away. It has two parts: a call to `Drop::drop` if the type implements the `Drop` trait, and then the automatically generated **drop glue** that destroys every field. The compiler inserts the destructor call itself, at the point where the owning variable goes out of scope, so a resource such as a pooled database connection is released whichever way the scope is left: falling off the end of the block, an early `return`, a `?`, or unwinding from a panic. A guard type for a connection pool usually looks like this: ```rust struct PooledConn { id: u32 } impl Drop for PooledConn { fn drop(&mut self) { println!("conn {} back in pool", self.id); } } ``` ## Why an explicit `drop()` call is E0040 The signature is the clue: `fn drop(&mut self)` **borrows** the value, it does not consume it. If you could write `conn.drop()`, then after the call: - `conn` would still be in scope and usable, even though its connection had been handed back; - the compiler would still run the destructor at the end of the scope, releasing the same connection a second time. Both are exactly the bugs the trait exists to prevent, so rustc rejects every explicit call, whether written as a method (`conn.drop()`) or as a path (`Drop::drop(&mut conn)`), with **E0040**, "explicit use of destructor method". The compiler's own help line suggests the fix: `drop(conn)`. ## Releasing early with `std::mem::drop` `std::mem::drop` is in the prelude, so `drop(conn)` needs no import. Its definition is literally an empty generic function: ```rust pub fn drop<T>(_x: T) {} ``` Nothing in the body is special. Because the parameter is taken **by value**, calling it **moves** the guard into the function; when the function returns, its parameter goes out of scope and the destructor runs there. The effects, in order: 1. The guard is moved out of `conn`, so the caller can no longer touch it; any later use is E0382, "borrow of moved value". 2. `Drop::drop` runs once, at the call site, and the connection is back in the pool. 3. At the end of the original scope nothing more happens, because the compiler knows `conn` was moved. This is why the early release pattern matters in practice: a request handler that runs one query and then spends seconds rendering a report should hand the connection back before the rendering, not after it. ## Conditional release and drop flags Early release does not have to happen on every path. If `drop(conn)` sits inside one branch of an `if`, the guard is moved on that path only. When the compiler cannot tell statically whether a variable is still initialised at the end of its scope, it keeps a hidden **drop flag** for it on the stack and checks the flag there. The result is the same guarantee as before: the destructor runs **exactly once**, either at the `drop` call or at the end of the scope, never both and never zero times. You get this without writing any bookkeeping yourself. ## Other ways to end a value's life early | Technique | Destructor runs | Notes | |---|---|---| | `drop(conn)` | now, once | the usual choice; `conn` is moved | | inner block `{ let conn = ...; }` | at the closing brace | good when several values share the short life | | `conn = checkout(2)` (assignment) | old value dropped now | needs `let mut conn`; reuses the variable for a new guard | | `std::mem::forget(conn)` | never | leaks the connection; safe but almost always a bug | ## Mistakes that look like early release - `drop(&conn)` moves a **reference** into `drop`, which drops nothing; rustc warns with the `dropping_references` lint and the guard lives to the end of the scope. - `drop(x)` on a `Copy` value such as an integer drops a copy; the original stays usable, and the `dropping_copy_types` lint warns. - `drop(conn)` cannot free a value that is still borrowed: if a `&conn` is alive later in the function, the move is rejected by the borrow checker, so there is no dangling reference to worry about. - Calling `drop` is never required for correctness; it only moves the release point earlier than the end of the scope.
- What is inside `std::mem::drop`, and how can it run a destructor?Its body is empty: `pub fn drop<T>(_x: T) {}`. The parameter is taken by value, so the call moves the argument in, and when the function returns its parameter goes out of scope like any local, which runs the destructor. There is no compiler magic beyond ordinary move and scope rules.
- A teammate writes `drop(&conn)` to release the connection early. What happens?Nothing useful. `drop` receives a `&PooledConn`, and dropping a reference does nothing to the value behind it. rustc warns with `dropping_references`, and the guard still lives until the end of its scope. The fix is `drop(conn)`, which moves the guard itself.
- Can `drop(conn)` free a guard while some `&conn` is still in use later in the function?No. Passing `conn` to `drop` is a move, and the borrow checker rejects moving a value while a borrow of it is still live (E0505, move out of a borrowed value). Either finish using the reference first or restructure so the borrow ends before the move.
- Calling conn.drop() is fine as long as conn is not used afterwards.
- drop(&conn) returns the connection to the pool early.
- Every Drop type must be dropped by hand or its resource leaks.
- std::mem::drop is a compiler intrinsic that bypasses the move rules.
- Rust frees values whenever the allocator decides, so release time is unpredictable.