A Rust pool guard must hand its connection back inside Drop and also offer `detach(self)`; why does moving `self.conn` out fail in both, and how do you fix it?
answer
- drop only gets a mutable borrow
- Drop needs the whole value later
- leave something behind in the field
- a wrapper that suppresses the destructor
basics
~20 sDrop::drop gets &mut self, so moving a field out is E0507; a by-value method on a Drop type cannot move a field out either (E0509), since drop still needs the whole value. Store Option<Connection> and take() it, or use ManuallyDrop with unsafe take.
solid answer
~40 sInside `drop(&mut self)` you only have a mutable borrow, and moving `self.conn` out of a borrow is E0507. In `detach(self)` you own the guard, but its type implements `Drop`, so its destructor will still run on the whole value; rustc refuses a partial move with E0509, "cannot move out of type ..., which implements the `Drop` trait". The safe fix is to make the field `Option<Connection>` and call `take()` in both places, leaving `None` so `drop` knows there is nothing to return. The zero-overhead alternative is `ManuallyDrop<Connection>`: `drop` calls the `unsafe` `ManuallyDrop::take`, and `detach` wraps `self` in `ManuallyDrop` to suppress the guard's own destructor before taking the field.
code
plaintext · 14 lineserror[E0507]: cannot move out of `self.conn` which is behind a mutable reference
--> src/main.rs:16:29
|
16 | self.pool.idle.push(self.conn);
| ^^^^^^^^^ move occurs because `self.conn` has type `Connection`, which does not implement the `Copy` trait
error[E0509]: cannot move out of type `PooledConn<'_>`, which implements the `Drop` trait
--> src/main.rs:22:9
|
22 | self.conn
| ^^^^^^^^^
| |
| cannot move out of here
| move occurs because `self.conn` has type `Connection`, which does not implement the `Copy` traitgo deeper
Know that a destructor only borrows the value, so it cannot move fields out of self directly.
Explain E0509: a type with Drop must stay whole for its destructor, so even a by-value method cannot partially move it; Option with take is the standard safe fix.
Choose between Option and ManuallyDrop deliberately, write the SAFETY argument for ManuallyDrop::take, and remember that wrapping self in ManuallyDrop leaks every other field unless handled.
Keep unsafe ManuallyDrop patterns inside small, reviewed container types, and let application guards use Option so the empty state is checked rather than assumed.
## The two compile errors A pool guard typically owns a `Connection` and a reference to the pool, and returns the connection in its destructor. Written the obvious way, it fails twice: - In `fn drop(&mut self)`, the expression `self.pool.idle.push(self.conn)` tries to **move** `self.conn` out from behind a mutable reference. Moving out of a borrow is **E0507**, "cannot move out of `self.conn` which is behind a mutable reference". `Drop::drop` never receives ownership, so this rule applies to every destructor. - In `fn detach(self) -> Connection { self.conn }`, the method does own the guard, so an ordinary struct would allow this **partial move**. But a type that implements `Drop` will have `Drop::drop(&mut self)` called on the **whole** value when it goes out of scope, and that method must find every field initialised. rustc therefore forbids moving any field out of such a type: **E0509**, "cannot move out of type `PooledConn<'_>`, which implements the `Drop` trait". Both errors share a root cause: a destructor needs a complete value to work on, so the field cannot be left empty without the type's cooperation. ## Fix 1: `Option` and `take` Make the field `conn: Option<Connection>`. `Option::take(&mut self)` moves the value out and leaves `None` in its place, which only needs a mutable borrow: 1. `drop` does `if let Some(conn) = self.conn.take() { self.pool.idle.push(conn); }`. 2. `detach(mut self)` does `self.conn.take().expect(...)`. The guard is still dropped at the end of `detach`, but its destructor finds `None` and does nothing. This is entirely safe code. Its costs are small but real: every access to the connection goes through `Option` (an `as_ref().unwrap()` or a match), and `Option<Connection>` may be larger than `Connection` when the type has no spare bit pattern for `None`. ## Fix 2: `ManuallyDrop` and `ManuallyDrop::take` `std::mem::ManuallyDrop<T>` is a zero-cost wrapper with the same layout as `T` that stops the compiler from dropping `T` automatically. You can read the value through it safely, because it implements `Deref`. - In `drop`, `unsafe { ManuallyDrop::take(&mut self.conn) }` moves the connection out. It is `unsafe` because it leaves the container unchanged: the caller must guarantee the slot is never used again. In a destructor that runs once, that holds. - In `detach(self)`, first wrap the whole guard: `let mut this = ManuallyDrop::new(self);`. That suppresses `PooledConn`'s own `Drop`, so taking `this.conn` cannot lead to a second return. Any other field with a destructor would now be leaked unless you drop it yourself. - `ManuallyDrop::into_inner` is the safe way to unwrap, but it takes the wrapper **by value**, so it cannot be used through `&mut self`; calling it on `self.conn` in `drop` is E0507 again. ## Choosing between them | | `Option<Connection>` + `take` | `ManuallyDrop<Connection>` + `take` | |---|---|---| | unsafe code | none | in `drop` and `detach` | | per-access cost | a `None` check on each use | none | | empty state visible to methods | yes, as `None` | no; reading after `take` would be a bug | | typical home | application guards | low-level containers and hot paths | Start with `Option`; move to `ManuallyDrop` when profiling or an API shape justifies the unsafe code. If `Connection` has a cheap placeholder value, `std::mem::replace(&mut self.conn, placeholder)` is a third safe option. ## Writing the SAFETY argument Every `unsafe` block in the `ManuallyDrop` version needs a short `SAFETY:` comment that a reviewer can check. For this guard the argument has three parts: - the compiler calls `Drop::drop` at most once per value, so the `take` inside it cannot run twice for the same slot; - nothing in `drop` reads `self.conn` after the `take`; - in `detach`, the wrapped `this` is never dropped or read again, and the guard's remaining field is a reference with nothing to clean up. If any of these stops being true, for example a later edit adds a method that reads `self.conn` after a partial teardown, the code becomes unsound without any compiler error. That fragility is the real price of the zero-cost version. ## Related rules worth knowing - `ManuallyDrop::drop` runs the inner destructor in place and is also `unsafe`, for the same reason. - The `ManuallyDrop` documentation warns that a public safe API, even a derived `Debug`, that can reach an already-dropped `ManuallyDrop` field can be unsound. - A type that implements `Drop` cannot also be `Copy`; that rule is covered with Copy and Clone.
- Why can't `drop` just call `ManuallyDrop::into_inner(self.conn)` and avoid `unsafe`?`into_inner` takes the `ManuallyDrop` by value, and `drop` only has `&mut self`, so the call is a move out of a borrow and fails with E0507. `ManuallyDrop::take` works through `&mut`, which is exactly why it must be `unsafe`: it copies the value out and leaves the slot looking full.
- After `let mut this = ManuallyDrop::new(self);` in `detach`, what happens to the guard's other fields?Nothing runs for them: wrapping `self` suppresses the whole destructor, including the drop glue for every field. A reference field needs no cleanup, but a field that owns a resource would leak unless `detach` takes it out and drops it explicitly.
- A method taking self by value can always move fields out of it.
- Cloning the connection inside drop is a correct way to return it to the pool.
- mem::forget(self) inside drop stops the destructor running twice.
- ManuallyDrop::take is safe because the wrapper prevents double drops.
- ManuallyDrop adds a heap allocation to hold the wrapped value.