Skip to content
Theory · Structs · lesson 3 of 8

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:

Rust
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:

  1. impl Order { … } is the block of actions for the type Order. Everything inside it belongs to the order.
  2. fn total(&self) -> u32 declares an action. Its first parameter &self is a reference to the order the action was called on.
  3. self.items * 50 reads the field through that reference: one portion costs 50.
  4. order.total() calls the action with a dot, and println! prints 150.

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:

  • &self reads it;
  • &mut self changes it;
  • self takes it whole.

Step through the program and watch what self receives in each call and what happens to order in the main frame.

LiveWhat self receivesstep 1 of 8 · frames: 1

order is a slip with one portion, and let mut allows it to change.

Watch what self receives in each call and what becomes of order

&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:

Rust
struct Order {
    items: u32,
}

impl Order {
    fn submit(self) {
        println!("sent {}", self.items);
    }
}

fn main() {
    let order = Order { items: 3 };
    order.submit();
    order.submit(); // ✗
}
TEXT
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:

  • &self takes a reference for reading: the method does not change the value, and you can call it on any variable;
  • &mut self takes a mutable reference: the method changes the fields, and the variable needs mut;
  • self takes 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:

Rust
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); // ✗
}
TEXT
error[E0596]: cannot borrow `order` as mutable, as it is not declared as mutable

The 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 impl block; its first parameter self is the value the method was called on.
  • &self reads, &mut self changes, self takes the whole value.
  • The dot takes & or &mut by itself: order.total() is the same as Order::total(&order).
  • A &mut self method needs let mut (E0596), and after a self method the variable is moved (E0382).