Sub topic 8
Methods: self, &self, and &mut self
This chapter assumes you can write a struct and an impl block, and that you know the basics of moves, &, and &mut. It covers how a method's first parameter decides what the method may do with the value.
A method is a function with a receiver
A method is a function inside an impl block whose first parameter is named self. That parameter is the receiver. Its type is shorthand for the type being implemented:
| Written as | Expands to | The method can |
|---|---|---|
| `&self` | `self: &Self` | Read fields. The caller keeps the value. |
| `&mut self` | `self: &mut Self` | Read and change fields. The caller keeps the value. |
| `self` | `self: Self` | Take ownership. The caller can no longer use the value. |
Without a receiver, the function is an associated function such as new. You call it as Type::name(...), not on an instance.
The three receivers in one program
#[derive(Debug)]
struct Counter {
count: u32,
}
impl Counter {
fn new() -> Self {
Self { count: 0 }
}
fn get(&self) -> u32 {
self.count
}
fn increment(&mut self) {
self.count += 1;
}
fn finish(self) -> u32 {
self.count
}
}
fn main() {
let mut c = Counter::new();
c.increment();
c.increment();
println!("{}", c.get());
let total = c.finish();
println!("{total}");
// println!("{}", c.get()); // error[E0382]: borrow of moved value: `c`
}get borrows c immutably, so c is still usable afterward. increment borrows it mutably, which requires the binding to be declared let mut. finish moves c into the method, so the last line would not compile if you uncommented it.
Choosing a receiver
Start with the weakest access that works, and widen only when the method needs it.
Use self when the method turns the value into something else, as into_dimensions does in a Rectangle, or when it hands the fields to a new owner. Methods named into_* conventionally take self.
Common errors
- E0596, cannot borrow as mutable. You called a
&mut selfmethod on a binding declared withoutmut. Addmutto thelet. - E0382, use of moved value. You called a
selfmethod and then used the value again. Either stop using it, or change the method to borrow if it doesn't need to consume. - E0507, cannot move out of borrowed content. A
&selfmethod tried to return an owned field such as aString. Return a reference (&str) or call.clone().
Exercise
A struct Log holds a Vec<String> of messages. Which receiver should add(&mut self, msg: &str), len(&self), and into_messages(self) use, and why does into_messages need the third form?
Show answer
add needs &mut self because it pushes onto the vector. len needs only &self because it reads. into_messages uses self because it returns the Vec<String> by value, which moves the field out of the struct. A &self receiver cannot move a field out, so the struct must be consumed.