Methods and self
In the previous lesson the form only stored data. Now let's teach it some actions.
Picture an order slip in a café with a "Portions" field. You can do three different things with the slip: read it and work out the total, add portions, or hand it in to the kitchen. Many people can read the slip, only the one holding it can write on it, and a slip handed in to the kitchen never comes back to you.
You could work out the total with an ordinary function fn total(order: &Order) -> u32. But then the action lives apart from the slip, and nothing in the code shows that it belongs to the order. In Rust you gather a type's actions in an impl block:
struct Order {
items: u32,
}
impl Order {
fn total(&self) -> u32 {
self.items * 50
}
}
fn main() {
let order = Order { items: 3 };
println!("{}", order.total()); // 150
}Let's walk through the example line by line:
impl Order { … }is the block of actions for the typeOrder. Everything inside it belongs to the order.fn total(&self) -> u32declares an action. Its first parameter&selfis a reference to the order the action was called on.self.items * 50reads the field through that reference: one portion costs 50.order.total()calls the action with a dot, andprintln!prints150.
The method and self
A method is a function in an impl block whose first parameter is called self: the value the method was called on. &self is short for self: &Self, and Self stands for the type named in the impl header, here Order.
The call order.total() is the same function as Order::total(&order). The dot takes the reference &order by itself and passes it as self. The familiar s.len() works the same way: the method gets a reference to the string even though you write no &.
Three kinds of self
The first parameter decides what the method may do with the slip:
&selfreads it;&mut selfchanges it;selftakes it whole.
Step through the program and watch what self receives in each call and what happens to order in the main frame.
1struct Order {2 items: u32,3}4 5impl Order {6 fn total(&self) -> u32 {7 self.items * 508 }9 10 fn add(&mut self, n: u32) {11 self.items += n;12 }13 14 fn submit(self) {15 println!("sent {}", self.items);16 }17}18 19fn main() {20 let mut order = Order { items: 1 };21 println!("{}", order.total());22 order.add(2);23 println!("{}", order.total());24 order.submit();25}
order is a slip with one portion, and let mut allows it to change.
&self reads
The method gets a & reference, like a reader of a book. It cannot change the fields, and you can call it on any variable, with or without mut. Most methods are declared this way: everything that only looks at the value, such as a total, a length or a check.
&mut self changes
The method gets a mutable reference and can change the fields: self.items += n changes order itself. Again the dot takes the reference by itself, this time &mut order. And as you already know, a mutable reference can be taken only from a variable declared with mut. That is why order.add(2) compiles only with let mut order.
self takes the value
Without & the method gets the whole value: the slip moves into the parameter self, as a string moves into a function parameter. At the method's } the value is destroyed unless the method returns it. Such methods are written for the last action on a value: handing in a slip, turning the value into something else. After the call you cannot use the original variable:
struct Order {
items: u32,
}
impl Order {
fn submit(self) {
println!("sent {}", self.items);
}
}
fn main() {
let order = Order { items: 3 };
order.submit();
order.submit(); // ✗
}error[E0382]: use of moved value: `order`The first call took the slip, and order is moved: there is nothing left to hand to the second call.
This is where the slip analogy falls short. In a café you can tell who reads the slip and who writes on it only by what they do. In Rust it is written in the method's declaration: the first parameter tells you right away what the method will do with your value, and the compiler checks it.
Interviewers like to ask this: "What is the difference between &self, &mut self and self?" The answer:
&selftakes a reference for reading: the method does not change the value, and you can call it on any variable;&mut selftakes a mutable reference: the method changes the fields, and the variable needsmut;selftakes the value: after the call the variable is moved;- give a method the weakest kind that is enough for it.
Common mistake
A &mut self method is called on a variable without mut:
struct Order {
items: u32,
}
impl Order {
fn add(&mut self, n: u32) {
self.items += n;
}
}
fn main() {
let order = Order { items: 1 };
order.add(2); // ✗
}error[E0596]: cannot borrow `order` as mutable, as it is not declared as mutableThe program does not compile: the dot takes &mut order, and a variable without mut gives no mutable reference. The method itself is written correctly, and this is a build error, not a panic. The fix is let mut order.
Key points
- A method is declared in an
implblock; its first parameterselfis the value the method was called on. &selfreads,&mut selfchanges,selftakes the whole value.- The dot takes
&or&mutby itself:order.total()is the same asOrder::total(&order). - A
&mut selfmethod needslet mut(E0596), and after aselfmethod the variable is moved (E0382).