In Rust, how do you choose between `self`, `&self` and `&mut self` for a method, and what does each leave the caller holding?
answer
- what the body is allowed to do
- read, change in place, or consume
- shorthand for self: &Self
- the caller after a by-value call
- let mut and E0596
basics
~20 sPick the weakest receiver the body needs: &self to read, &mut self to change fields in place, self to consume or convert. The caller keeps its value after the first two; self moves it away unless the type is Copy.
solid answer
~40 sThe receiver is the method's first parameter and it states what the call may do to the value. `&self` (short for `self: &Self`) is a shared borrow: the method can read fields and the caller keeps the value. `&mut self` is an exclusive borrow: the method can assign fields, the caller keeps the value, and an owned variable must be declared `let mut` or rustc reports E0596. `self` takes ownership: the method can take fields apart or turn the value into something else, and afterwards the caller's variable is moved, so using it is E0382, unless the type is `Copy`. The rule is to choose the weakest receiver that works: `reading(&self)`, `set_target(&mut self, ..)`, `into_report(self)`.
code
rust · 32 linesstruct Thermostat {
room: String,
target: f64,
current: f64,
}
struct Report {
room: String,
drift: f64,
}
impl Thermostat {
fn reading(&self) -> f64 {
self.current
}
fn set_target(&mut self, target: f64) {
self.target = target;
}
fn into_report(self) -> Report {
Report { room: self.room, drift: self.current - self.target }
}
}
fn main() {
let mut t = Thermostat { room: String::from("lab"), target: 20.0, current: 18.5 };
println!("reading {}", t.reading()); // shared borrow for the call
t.set_target(21.0); // exclusive borrow for the call
let report = t.into_report(); // t is moved into the method
println!("{} drift {}", report.room, report.drift);
}go deeper
Know the three receivers by heart and what each allows: read, change in place, consume. Be able to say why calling a method again after into_report fails.
Explain the receivers as shorthands for self: Self, &Self and &mut Self, and name E0596 and E0382 as the errors a wrong receiver or binding produces.
Show that receiver choice is API design: self forces clones on callers that still need the value, &mut self locks out other borrows for the call, and the weakest receiver keeps callers flexible.
Treat receivers as the contract a type publishes: consuming methods mark one-way conversions, and a review rule of the weakest receiver that works keeps a codebase's types easy to share.
## The receiver is an ordinary parameter with a shorthand A **method** in Rust is a function inside an `impl` block whose first parameter is named `self`. That parameter is called the **receiver**, and its type decides what the method may do with the value it is called on. The Reference defines three shorthands: | Shorthand | Full form | Kind of access | |---|---|---| | `self` | `self: Self` | ownership: the value moves into the method | | `&self` | `self: &Self` | shared borrow: read only | | `&mut self` | `self: &mut Self` | exclusive borrow: read and write | `Self` is an alias for the type the `impl` block is for, so inside `impl Thermostat`, `&self` means `self: &Thermostat`. Because the receiver is just a parameter, everything the borrow rules say about `&T`, `&mut T` and owned `T` arguments applies to it unchanged. ## What each receiver lets the body do Take a `Thermostat` with three methods: - `fn reading(&self) -> f64` reads `self.current`. Assigning `self.target = 21.0` here fails with **E0594** ("cannot assign to `self.target`, which is behind a `&` reference"). - `fn set_target(&mut self, target: f64)` assigns `self.target`. It cannot move a non-`Copy` field such as a `String` out of `self`, because the caller still owns the struct and expects it whole afterwards. - `fn into_report(self) -> Report` owns the thermostat, so it can move `self.room` into the report without cloning. When the method returns, whatever it did not move out is dropped. ## What the caller is left holding This is the half of the answer interviewers listen for: 1. After `t.reading()` the caller still owns `t`, unchanged, and other shared borrows could have run at the same time. 2. After `t.set_target(21.0)` the caller still owns `t`, now changed. For the duration of the call no other reference to `t` may be in use, and `t` must be declared `let mut t`; otherwise rustc reports **E0596** ("cannot borrow `t` as mutable, as it is not declared as mutable"). 3. After `let report = t.into_report();` the caller no longer owns `t`. Any later use is **E0382** ("borrow of moved value: `t`"), and rustc adds a note that `Thermostat::into_report` takes ownership of the receiver `self`. The one exception is a `Copy` type: a `self` method on a small `Copy` newtype receives a copy and the caller's value stays usable. The dot call itself needs no `&` or `&mut`: method lookup borrows the receiver automatically (that lookup is covered with references), so `t.set_target(21.0)` and `Thermostat::set_target(&mut t, 21.0)` are the same call. ## How to choose - Start from `&self`. Many methods only read, and a shared borrow lets callers keep several references at once. - Move to `&mut self` when the method must change the value in place and the caller keeps using it afterwards. - Use `self` when the method **consumes** the value: it converts it into another type (`into_report`), hands its fields to someone else without cloning, or must stop the caller from using the old value. The Rust book calls this rare. The `into_` prefix is the usual signal in std, as in `String::into_bytes`. - Do not take `self` just to avoid a borrow: it forces every caller that still needs the value to clone it first. ## The receiver borrows the whole value A method signature cannot say which fields it touches, so the borrow covers the whole struct for the duration of the call: - While `let r = &t.room;` is still in use, writing `t.target = 5.0` directly compiles, because the compiler sees two different fields. - Calling `t.set_target(21.0)` at that point fails with **E0502** ("cannot borrow `t` as mutable because it is also borrowed as immutable"), because `&mut self` borrows all of `t`, `room` included. This is one reason to keep `&mut self` methods small and to prefer `&self` wherever a method only reads: every `&mut self` call briefly excludes all other access to the value. ## Variations worth recognising - `mut self` is still ownership; `mut` only makes the method's local binding mutable. The caller has lost the value either way. - The Reference also accepts `self: Box<Self>`, `self: Rc<Self>`, `self: Arc<Self>` and `self: Pin<&mut Self>`, nested inside references; you meet them with trait objects and futures rather than in everyday struct code. - A function in the `impl` block with no `self` parameter is an **associated function**, called as `Thermostat::new(..)`, not a method.
- When is taking `self` the right choice even though it is rare?When the method turns the value into something else and the old value would be meaningless afterwards, such as `into_report` reusing the `String` it owns instead of cloning it. It also suits small `Copy` types, where `self` costs a copy and leaves the caller's value intact, which is why `f64::abs` takes `self`.
- What is the difference between `mut self` and `&mut self`?`mut self` moves the value into the method and lets the method change its own local copy; the caller has lost the value and sees nothing unless the method returns it. `&mut self` borrows the caller's value exclusively, so every change is visible to the caller, who still owns the value after the call.
- Why can a `&mut self` method not move a `String` field out of `self`?The caller still owns the struct and will use or drop it after the call, so the struct must stay whole. Moving the field out would leave a hole, and rustc rejects it with E0507. The method can replace the field with another value instead, which swaps rather than leaves it empty.
Lending a notebook: let a colleague read it (&self), hand it over to be annotated and returned (&mut self), or give it away for good (self). Only in the last case do you no longer have a notebook.
- A &self method copies the whole struct into the method
- self and &self differ only in syntax; the caller keeps the value either way
- A &mut self method can be called on a binding declared without mut
- Taking self by value is the default; borrow only to save a copy
- A &self method may assign a field if nothing else is borrowing it