Sub topic 9
How method calls resolve receivers
This chapter assumes you can define a struct, write an impl block, and tell self, &self, and &mut self apart. It explains how the compiler turns value.method() into a real function call, and why the same method works on a value, a reference, or a Box.
Method syntax is sugar for a function call
A method is a function whose first parameter is named self. The call r.area() is shorthand for Rectangle::area(&r). Rust has no separate -> operator like C and C++. The compiler looks at the method's declared receiver and adjusts the expression on the left of the dot to match.
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn scale(&mut self, factor: u32) {
self.width *= factor;
self.height *= factor;
}
fn into_dimensions(self) -> (u32, u32) {
(self.width, self.height)
}
}
fn main() {
let mut r = Rectangle { width: 3, height: 4 };
println!("{}", r.area());
println!("{}", Rectangle::area(&r));
r.scale(2);
Rectangle::scale(&mut r, 2);
let boxed = Box::new(Rectangle { width: 1, height: 2 });
let rr = &&r;
println!("{}", rr.area());
println!("{}", boxed.area());
let (w, h) = r.into_dimensions();
println!("{w}x{h}");
}The program prints 12, 12, 192, 2, and 12x16. The calls on rr and boxed compile even though area takes &Rectangle and neither variable has that type. The lookup algorithm below explains why.
The lookup algorithm
For an expression expr.name(args), the compiler works in two stages.
- It builds a list of candidate receiver types. It starts with the type of
expr, call itT. It then repeatedly dereferences:*T,**T, and so on, following built-in reference dereferencing and theDereftrait. If the chain ends in an array type, it adds the unsized slice type as a last step. - For each type
Uin that list, in order, it triesU, then&U, then&mut U. For each of these it looks for a method namednamewhose receiver type is exactly that type. Inherent methods (fromimpl Type) are checked before trait methods.
The first match wins. The compiler then inserts the needed operations: dereferences, a borrow (& or &mut), or neither. Adding a borrow is called autoref.
Applied to rr.area() with rr: &&Rectangle, the candidates in order are:
| Step | Candidate receiver | Matches `area(&self)`? |
|---|---|---|
| 1 | `&&Rectangle` | No |
| 2 | `&&&Rectangle` | No |
| 3 | `&mut &&Rectangle` | No |
| 4 | `&Rectangle` (after one dereference) | Yes |
The compiler dereferences rr once and calls Rectangle::area with the result. For boxed.area(), the Box<Rectangle> derefs to Rectangle. The compiler then autorefs it to &Rectangle, which matches.
What each receiver form needs
The receiver you declare decides what the call site must be able to provide.
| Declared receiver | Call site must have | Effect on the caller |
|---|---|---|
| `&self` | Any readable access | Value stays usable |
| `&mut self` | A `mut` binding or an existing `&mut` | Value is mutably borrowed during the call |
| `self` | Ownership of the value | Value is moved (unless the type is `Copy`) |
Autoref only creates borrows from places you are allowed to borrow. Writing r.scale(2) when r was declared without mut fails, because the compiler cannot create &mut r from an immutable binding.
Common errors
Calling a consuming method through a reference
Suppose a function receives &Rectangle and calls r.into_dimensions(). The lookup finds into_dimensions at the Rectangle step, after dereferencing. That step needs ownership, but the value sits behind a shared reference. The compiler reports error E0507, "cannot move out of *r which is behind a shared reference". The lookup did its job. The method simply cannot be used here.
You have three options. You can take Rectangle by value in the function, change the method to &self, or clone first when the type implements Clone.
#[derive(Debug, Clone)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn into_dimensions(self) -> (u32, u32) {
(self.width, self.height)
}
}
fn dimensions_of(r: &Rectangle) -> (u32, u32) {
r.clone().into_dimensions()
}
fn main() {
let r = Rectangle { width: 2, height: 5 };
println!("{:?}", dimensions_of(&r));
println!("{:?}", r);
}Using a value after a consuming call
r.into_dimensions() moves r. Any later use of r gives "borrow of moved value". This is ordinary ownership, but it surprises people because the call looks like any other method call. Check the signature when a variable stops working after a call.
Field versus method with the same name
A struct can have both a field width and a method width(). The syntax r.width reads the field, and r.width() calls the method. They do not conflict. Forgetting the parentheses gives an error like "attempted to take value of method". Forgetting that a field is private outside its module gives a privacy error instead.
Inherent methods hide trait methods
When an inherent method and a trait method have the same name and the same receiver, the inherent method wins. Fully qualified syntax selects the trait version explicitly.
trait Describe {
fn name(&self) -> String;
}
struct Dog;
impl Dog {
fn name(&self) -> String {
"inherent".to_string()
}
}
impl Describe for Dog {
fn name(&self) -> String {
"trait".to_string()
}
}
fn main() {
let d = Dog;
println!("{}", d.name());
println!("{}", Describe::name(&d));
println!("{}", <Dog as Describe>::name(&d));
}This prints inherent, trait, and trait.
A surprising result: `clone` on a reference
Candidate order is by type, not by what you meant. The following program shows the effect.
#[derive(Debug, Clone)]
struct Cloneable {
id: u32,
}
#[derive(Debug)]
struct Plain {
id: u32,
}
fn main() {
let c = Cloneable { id: 1 };
let rc = &c;
let owned: Cloneable = rc.clone();
let p = Plain { id: 2 };
let rp = &p;
let copied_ref: &Plain = rp.clone();
println!("{:?} {:?}", owned, copied_ref);
}The program prints Cloneable { id: 1 } Plain { id: 2 }. For rc.clone(), the first candidate is &Cloneable by value. Clone::clone for Cloneable takes &Cloneable, so it matches and returns a Cloneable. Plain does not implement Clone. For rp.clone(), the by-value candidate &Plain finds nothing. Autoref then tries &&Plain, which matches Clone for &Plain, because shared references are always Clone. The result is another &Plain, not a Plain. The compiler may warn about this with the noop_method_call lint.
Practical guidance
- Do not write
(&r).area()or(*r).area(). The compiler inserts those operations for you. - Use the explicit form
Type::method(&value)when you want to name which implementation runs, or when you pass a method as a function, as in.map(Rectangle::area). - When a method call fails to compile, list the candidate types by hand. The error usually comes from what the winning method requires, not from the lookup.
Exercise
Given let mut b = Box::new(Rectangle { width: 1, height: 2 });, which candidate receiver type does b.scale(2) match, where scale takes &mut self? Why does the call fail if b is declared without mut?
Show answer
The candidates are tried in order: Box<Rectangle>, &Box<Rectangle>, &mut Box<Rectangle>, then, after dereferencing the box, Rectangle, &Rectangle, and &mut Rectangle. Only the last has the receiver type scale declares, so the compiler calls Rectangle::scale(&mut *b, 2). Without mut, the binding b does not allow a mutable borrow of the Box contents, so the compiler cannot create &mut *b and rejects the call.