skip to content

When rustc resolves `inv.total()`, how do auto-referencing and auto-dereferencing make it work for `Inventory`, `&Inventory` and `Box<Inventory>` receivers?

level: middleimportance: should knowfreq 42%

answer

  1. the dot does the borrowing
  2. a list of candidate receiver types
  3. T, then &T, then &mut T, then deref
  4. mutability is checked after lookup

basics

~20 s

For a method call, rustc builds candidate receiver types by repeatedly dereferencing the receiver, adding &T and &mut T after each, and picks the first that has a matching method. So inv.total() becomes Inventory::total(&inv) whatever pointer inv is.

solid answer

~40 s

Method calls are the one place Rust borrows and dereferences for you. The Reference describes the lookup: start from the receiver's type, repeatedly dereference it (through `&`, `&mut` and any `Deref` impl such as `Box`), finally try an unsized coercion such as array to slice, and after each type `T` add `&T` and `&mut T`. For each candidate in that order, rustc looks for an inherent method, then a trait method, with that receiver type. So `owned.total()` auto-refs to `&owned`, `boxed.total()` derefs the `Box` then auto-refs. Mutability is checked only after a method is picked, so calling a `&mut self` method on a non-`mut` binding fails with E0596. Plain function arguments get none of this: `total(inv)` with an owned `inv` is E0308.

code

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

impl Inventory {
    fn total(&self) -> u32 {
        self.stock.iter().sum()
    }
    fn restock(&mut self, qty: u32) {
        self.stock.push(qty);
    }
}

fn main() {
    let mut owned = Inventory { stock: vec![3, 5] };
    owned.restock(2); // auto-ref: Inventory::restock(&mut owned, 2)
    let shared: &Inventory = &owned;
    let double: &&Inventory = &shared;
    let boxed: Box<Inventory> = Box::new(Inventory { stock: vec![4] });
    // owned.total() is Inventory::total(&owned)
    // double.total() derefs &&Inventory down to &Inventory
    // boxed.total() derefs Box<Inventory> through Deref, then auto-refs
    println!("{} {} {} {}", owned.total(), shared.total(), double.total(), boxed.total());
}

go deeper

for a junior

Know that the dot adds & or &mut to match self, &self or &mut self, and that ordinary function arguments need the & written out.

for a middle

Explain the candidate list: by value, &T, &mut T, then dereference through & or Deref and repeat, with an unsized coercion at the end, inherent before trait methods.

for a senior

Use the procedure to diagnose surprises: E0596 after lookup, a trait &self method beating an inherent &mut self method, and Deref types such as Box exposing their target's methods.

for a principal

Be wary of APIs that lean on lookup order: same-named inherent and trait methods with different receivers confuse readers, so a team convention against them prevents subtle calls.

## The convenience and why it exists Rust is strict about `&` and `&mut` everywhere except one spot: the **receiver** of a method call, the expression before the dot. With an inventory type ```rust impl Inventory { fn total(&self) -> u32 { self.stock.iter().sum() } fn restock(&mut self, qty: u32) { self.stock.push(qty); } } ``` you write `inv.total()` whether `inv` is an `Inventory`, a `&Inventory`, a `&&Inventory` or a `Box<Inventory>`, and `inv.restock(2)` on a `let mut` binding without typing `&mut`. That is **auto-referencing** (adding `&` or `&mut`) and **auto-dereferencing** (removing pointer layers) in method lookup. ## The lookup procedure The Rust Reference's section on method-call expressions defines it: 1. **Build the candidate list.** Take the receiver's type and dereference it repeatedly, adding each type reached. Dereferencing goes through `&`, `&mut` and any type implementing `Deref`, such as `Box`. At the end, try an unsized coercion (for example `[i32; 2]` to `[i32]`) and add the result if it works. 2. **Add the auto-refs.** After each candidate `T`, insert `&T` and `&mut T`. 3. **Search in order.** For each candidate type, look for a visible method whose receiver has exactly that type: first `T`'s inherent methods, then methods of visible traits implemented by `T`. 4. **Check what the search ignored.** The search does not consider mutability, lifetimes or `unsafe`. If the chosen method cannot be called for one of those reasons, it is a compile error. The Reference's own example: for a receiver of type `Box<[i32; 2]>` the candidates are `Box<[i32; 2]>`, `&Box<[i32; 2]>`, `&mut Box<[i32; 2]>`, `[i32; 2]`, `&[i32; 2]`, `&mut [i32; 2]`, `[i32]`, `&[i32]` and `&mut [i32]`. ## Walking the inventory cases | Receiver expression | Its type | First matching candidate | What actually runs | |---|---|---|---| | `owned.total()` | `Inventory` | `&Inventory` (auto-ref) | `Inventory::total(&owned)` | | `shared.total()` | `&Inventory` | `&Inventory` (by value) | `Inventory::total(shared)` | | `double.total()` | `&&Inventory` | `&Inventory` after one deref | `Inventory::total(*double)` | | `boxed.total()` | `Box<Inventory>` | `&Inventory` after deref through `Box` | `Inventory::total(&*boxed)` | | `owned.restock(2)` | `Inventory` | `&mut Inventory` (auto-ref) | `Inventory::restock(&mut owned, 2)` | ## Where it stops helping - **Mutability after the fact.** `let inv = Inventory { .. }; inv.restock(2);` finds `restock` through the `&mut Inventory` candidate, then fails: E0596, cannot borrow `inv` as mutable, as it is not declared as mutable. Through a `view: &Inventory`, the same call is E0596 with "`view` is a `&` reference". - **Ordinary arguments.** Auto-ref belongs to the receiver only. `total(inv)` where `total` takes `&Inventory` and `inv` is owned is E0308, mismatched types, with the hint "consider borrowing here". Separately, **deref coercion** can turn `&Box<Inventory>` into `&Inventory` at a typed argument, but it never adds the first `&`; its rules are covered with `Deref` and operators. - **Order surprises.** Because candidates are tried type by type, a `&self` trait method can win over a `&mut self` inherent method of the same name: for an owned receiver, `&T` comes before `&mut T`. The Reference shows exactly this case, and the trait method runs. ## Field access is similar, method lookup is richer Field access such as `double.stock` also dereferences automatically until it finds a struct with that field. It never needs auto-ref, because a field access names a place rather than calling a function with a receiver type. ## What to say in an interview - The dot operator inserts `&`, `&mut` or `*` to match a method's `self`, `&self` or `&mut self` receiver. - The search order is by value, then `&`, then `&mut`, then dereference and repeat. - It does not bypass the borrow rules: a `&mut self` method still needs a mutable place, and it still takes an exclusive borrow for the call. - Nothing like it happens for normal arguments, which is why you write `total(&inv)` but `inv.total()`. - Inside generic code, when the receiver's type is a type parameter `T`, the Reference says methods from `T`'s trait bounds are looked up first, then the remaining methods in scope. A good closing line: auto-ref and auto-deref change how much you type, never what is borrowed. Every `inv.total()` is still a shared borrow of `inv` for the call, and every `inv.restock(2)` is still an exclusive one.

  • Why does `total(inv)` fail when `inv.total()` works, for an owned `inv`?
    Auto-referencing is part of method-call lookup only. A plain function call checks the argument against the parameter type, `&Inventory`, finds `Inventory`, and reports E0308 with the hint to borrow. Deref coercion could adjust an existing reference at that site, but it never creates the first `&`.
  • If lookup finds a `&mut self` method but the receiver is behind a `&Inventory`, does rustc keep searching for another method?
    No. The search ignores mutability; once a method is chosen, rustc checks whether it can be called and reports E0596 if not. It does not fall back to a later candidate.

  • inv.total() only works if inv is already a reference.
  • Auto-referencing also applies to ordinary function arguments.
  • Auto-ref can call a &mut self method on a binding not declared mut.
  • Method lookup tries &mut T before &T for an owned receiver.
  • Box needs an explicit * before calling a method of its contents.