Sub topic 9
How method calls resolve receivers
This chapter assumes you know how to define a struct and write methods with self, &self, and &mut self. It also assumes you understand moves and borrows.
The problem automatic referencing solves
A method declares how it takes its receiver, but you rarely write that at the call site. You write c.get(), not (&c).get(). The compiler adds the &, &mut, or * for you. This is called automatic referencing and dereferencing.
struct Counter {
count: u32,
}
impl Counter {
fn get(&self) -> u32 {
self.count
}
fn bump(&mut self) {
self.count += 1;
}
fn finish(self) -> u32 {
self.count
}
}
fn main() {
let mut c = Counter { count: 0 };
c.bump();
println!("{}", c.get());
println!("{}", Counter::get(&c));
let r = &c;
println!("{}", r.get());
let b = Box::new(Counter { count: 5 });
println!("{}", b.get());
println!("{}", c.finish());
}This prints 1, 1, 1, 5, and 1. The second line uses the explicit form, Counter::get(&c), which means the same thing as c.get().
The lookup order
For a call value.method(), the compiler builds a list of candidate receiver types. It starts with the type of value, call it T. For each candidate it tries T, then &T, then &mut T. If none has a method with that name, it dereferences T (for example Box<Counter> to Counter) and repeats. The first match wins.
In the example, b.get() has Box<Counter> as its first candidate. Box<Counter> has no get, so the compiler dereferences it to Counter and finds get(&self).
What the compiler checks after it picks a method
Resolution picks the method. Ownership rules then decide whether the call is allowed.
| Call | Method needs | Requirement |
|---|---|---|
| `c.bump()` | `&mut Counter` | `c` is declared `mut`, or you hold a `&mut` |
| `c.get()` | `&Counter` | Any access to the value |
| `c.finish()` | `Counter` by value | `c` is moved and can't be used again |
| `r.finish()` where `r: &Counter` | `Counter` by value | Error, unless `Counter` is `Copy` |
The last row is a common mistake. Automatic referencing never turns a reference into an owned value. If you only hold &Counter, you can't call a method that takes self. The compiler reports "cannot move out of *r which is behind a shared reference."
Common errors
- Calling a
&mut selfmethod on a binding declared withoutmut. Addmutto the binding. - Using a value after calling a
selfmethod on it. Use a&selfmethod, or clone first. - Expecting
&selfand&mut selfmethods of the same name to coexist on one type. A type can't define two methods with the same name in the sameimpl. Give them different names, such asgetandget_mut.
Exercise
Given let r = &mut c; where c is a Counter, which of r.get(), r.bump(), and r.finish() compile, and why?
Show answer
r.get() and r.bump() compile. The compiler reborrows *r as &Counter or &mut Counter. r.finish() does not compile, because finish takes self by value and you can't move a Counter out from behind a reference.