skip to content

In Rust, how can a function pass its `&mut Inventory` parameter to two calls in a row when `&mut T` is not `Copy`?

level: middleimportance: should knowfreq 40%

answer

  1. a shorter borrow of a borrow
  2. &mut *r
  3. inserted where the type is known
  4. generic T parameters move instead

basics

~20 s

Each call reborrows: where the parameter type is known to be &mut Inventory, the compiler passes a fresh &mut *inv for the call instead of moving inv, so inv is usable afterwards. A generic T parameter moves it instead.

solid answer

~40 s

A **reborrow** is a new reference taken through an existing one, written `&mut *r` (or `&*r` for a shared one). It borrows the original for a shorter span: while the reborrow is in use, `r` is frozen, and when it ends `r` is usable again. rustc inserts this implicitly wherever the expected type is already known to be a `&mut` type, such as a call to `fn restock(inv: &mut Inventory, ..)`, a `let` with an explicit `&mut Inventory` annotation, or a method receiver. That is why `restock(inv, 1); restock(inv, 2);` compiles. Where the expected type is a generic `T`, or a `let` has no annotation, there is nothing to coerce to, so the `&mut` is moved and a later use fails with E0382; rustc's help then suggests writing `&mut *inv` yourself.

code

rust · 23 lines
rust
struct Inventory {
    stock: Vec<u32>,
}

fn restock(inv: &mut Inventory, qty: u32) {
    inv.stock.push(qty);
}

fn nightly_restock(inv: &mut Inventory) {
    restock(inv, 1); // implicit reborrow: &mut *inv
    restock(inv, 2); // inv is still usable
    let r: &mut Inventory = inv; // annotated let: also a reborrow
    r.stock.push(3);
    let explicit = &mut *inv; // explicit reborrow
    explicit.stock.push(4);
    inv.stock.push(5); // the reborrows have ended
}

fn main() {
    let mut inv = Inventory { stock: vec![] };
    nightly_restock(&mut inv);
    println!("{:?}", inv.stock);
}

go deeper

for a junior

Know that a &mut parameter can be passed on to several helper calls and that &mut *r is the explicit way to write a reborrow.

for a middle

Explain that a reborrow freezes the original while it lives, and list where the compiler inserts it: typed parameters, annotated lets and method receivers.

for a senior

Diagnose the generic-parameter E0382: inference gives T = &mut Inventory, so there is no coercion site and the reference moves. Fix with &mut *r or a &mut U signature.

for a principal

When designing generic helpers in a shared crate, prefer signatures that name &mut U when callers will hand in borrows, so the implicit reborrow keeps working and callers need no explicit &mut * at each call site.

## The puzzle A `&mut T` is **not** `Copy`: the Rust Reference says a mutable reference that has not been borrowed from is the only way to access its value, so it cannot be duplicated. Passing a non-`Copy` value normally moves it. Yet this compiles: ```rust fn nightly_restock(inv: &mut Inventory) { restock(inv, 1); restock(inv, 2); // inv still usable } ``` The answer is **reborrowing**. ## What a reborrow is A **reborrow** creates a new reference by dereferencing an existing one and borrowing again: - `&mut *inv` is a new exclusive reference to the same `Inventory`, derived from `inv`. - `&*inv` is a new shared reference derived from `inv`. The new reference borrows *through* the old one. While the reborrow is in use, the original `inv` is frozen, exactly as an owner is frozen while it is borrowed. When the reborrow's last use passes, `inv` is active again. So exclusivity is never violated: at any moment only one of them is usable. The freeze is real. In this sequence rustc reports E0499, because `outer` is used while the reborrow `inner` is still going to be used: 1. `let outer = &mut inv;` 2. `let inner = &mut *outer;` 3. `outer.stock.push(1);` (rejected) 4. `inner.stock.push(2);` Swap lines 3 and 4 and it compiles, because `inner` is finished before `outer` is used. ## When the compiler reborrows for you rustc inserts `&mut *inv` implicitly when the place where `inv` is used already has a known `&mut` type. In practice: | Position | Example | Result | |---|---|---| | argument to a parameter typed `&mut Inventory` | `restock(inv, 1)` | implicit reborrow, `inv` usable afterwards | | `let` with an explicit type | `let r: &mut Inventory = inv;` | implicit reborrow | | method call receiver | `inv.stock.push(3)` through a `&mut` | reborrow through auto-referencing | | argument to a generic parameter `T` | `log_and_keep(inv)` with `fn log_and_keep<T>(item: T) -> T` | **move**, later use is E0382 | | `let` without a type | `let r = inv;` | **move**, later use is E0382 | The generic case surprises people. With `T` unconstrained, the compiler infers `T = &mut Inventory` from the argument itself; there is no separate expected type to coerce to, so the ordinary move happens. rustc's E0382 message says so: move occurs because `inv` has type `&mut Inventory`, which does not implement the `Copy` trait, and it suggests consider creating a fresh reborrow of `inv` here, with `&mut *inv`. ## Shared reborrows and downgrading You can also take a **shared reborrow** of a `&mut`: - `let peek: &Inventory = &*r;` reads through `r` without giving up `r` for good; - `let ro: &Inventory = r;` relies on the coercion from `&mut T` to `&T`, which the Reference lists among the allowed coercions. While a shared reborrow is in use, `r` can be read but not written. Writing through `r` and then reading `peek` afterwards is rejected with E0502, because `peek` is still live. ## Why this matters in real code - **Helper functions.** Splitting a long `&mut self` method into helpers that each take `&mut Inventory` works only because each call reborrows. - **Generic wrappers.** A logging or timing wrapper written as `fn timed<T>(x: T) -> T` silently consumes a `&mut` handed to it; take `&mut U` in the signature, or reborrow explicitly at the call site. - **Loops.** Calling `restock(inv, n)` inside a loop works for the same reason, with a fresh reborrow per iteration. - **`Option<&mut T>`.** The `Option` is not `Copy` either, and no reborrow is inserted through it: `if let Some(r) = opt` moves the reference out, and a second `if let` on `opt` fails with E0382. `opt.as_deref_mut()` hands out a fresh, shorter `Option<&mut Inventory>` each time, so `opt` stays usable. - **Shared references never need this.** `&T` is `Copy`, so passing it anywhere just copies the pointer. ## How to explain it in one breath A reborrow is a borrow of a borrow. It is shorter than the reference it comes from, it freezes that reference while it lives, and the compiler writes it for you whenever it already knows the target is a `&mut` type. When it does not know, as with a generic parameter or an unannotated `let`, you get a move, and writing `&mut *r` is the fix.

  • Why does `let r = inv;` move a `&mut Inventory` while `let r: &mut Inventory = inv;` does not?
    With the annotation, the `let` is a coercion site with a known `&mut` type, so the compiler inserts `&mut *inv`. Without it, the type of `r` is inferred from `inv`, nothing is coerced, and the non-`Copy` `&mut` is moved, so a later use of `inv` fails with E0382.
  • Can you still use the original `&mut` while a reborrow taken from it is live?
    No. The reborrow freezes the original until its last use. Using `outer` between `let inner = &mut *outer;` and a later use of `inner` is E0499. Once `inner` is finished, `outer` works again.

  • Passing a &mut to a function always moves it, so it can only be used once.
  • &mut T is Copy, which is why it can be passed to two calls.
  • A reborrow creates a second independent &mut usable at the same time as the first.
  • A generic fn f<T>(x: T) reborrows a &mut argument just like a concrete parameter.