Skip to content

Add Methods to a Struct

The Course
•
28 min study

With only plain functions, the code that works on a struct ends up scattered: add_minutes(&mut timer, 20) in one place, total(&timer) in another, and nothing to show they belong together. Methods put those functions on the type itself. A caller writes timer.add(20) and asks the value to do something, and the type's author decides how it is done and which rules apply.

An impl Timer block attaches functions to Timer. An associated function such as Timer::new() has no receiver and is called on the type, usually to build a value. A method's first parameter is its receiver, such as &self or &mut self, and it is called on a value with a dot. Inside an impl block, Self is another name for the type being implemented, here Timer.

Predict and run

Which method changes the Timer? What value does the other method read?

Predict, then run Rust
struct Timer {
    minutes: u32,
}

impl Timer {
    fn new() -> Self {
        Self { minutes: 0 }
    }

    fn add(&mut self, minutes: u32) {
        self.minutes += minutes;
    }

    fn total(&self) -> u32 {
        self.minutes
    }
}

fn main() {
    let mut timer = Timer::new();
    timer.add(20);
    println!("Total: {}", timer.total());
}
Check your prediction
Text
Total: 20

add takes &mut self, so it may change the timer. total takes &self, a shared borrow, so it can only read. The method call timer.add(20) is shorthand for Timer::add(&mut timer, 20): Rust borrows the value for you, in the way the receiver asks for.

Call timer.add(5) before printing and predict the new total. Then remove mut from the binding. The compiler flags the add calls with error[E0596]: cannot borrow timer as mutable, as it is not declared as mutable, but not the total call, which only needs to read.

Choose the receiver

The receiver says what a method needs from its value, in the same terms you learned on Day 3:

  • &self reads the value. The caller keeps it, and many reads can happen one after another.
  • &mut self changes the value. The caller's binding must be mut.
  • self takes ownership. The method uses the value up, and the caller cannot touch it afterward.

A consuming method fits a final step, such as turning a finished timer into a summary line.

Consume a timer into a summary Rust
struct Timer {
    topic: String,
    minutes: u32,
}

impl Timer {
    fn start(topic: &str) -> Self {
        Self { topic: String::from(topic), minutes: 0 }
    }

    fn add(&mut self, minutes: u32) {
        self.minutes += minutes;
    }

    fn finish(self) -> String {
        format!("{} took {} min", self.topic, self.minutes)
    }
}

fn main() {
    let mut timer = Timer::start("Methods");
    timer.add(15);
    timer.add(10);
    let summary = timer.finish();
    println!("{summary}");
}
Text
Methods took 25 min

format! works like println! but returns the text as a String instead of printing it. After timer.finish(), the timer has moved into the method. Adding timer.add(5); on the next line fails with error[E0382]: borrow of moved value: timer, which is exactly what you want: a finished timer should not keep counting.

Let a method enforce a rule

Because changes go through the method, the method is the one place to check them. This add refuses an empty session and returns true or false so the caller knows what happened.

Reject a change inside the method Rust
struct Timer {
    minutes: u32,
}

impl Timer {
    fn add(&mut self, minutes: u32) -> bool {
        if minutes == 0 {
            return false;
        }
        self.minutes += minutes;
        true
    }
}

fn main() {
    let mut timer = Timer { minutes: 0 };
    println!("Add 20: {}", timer.add(20));
    println!("Add 0: {}", timer.add(0));
    println!("Total: {}", timer.minutes);
}
Text
Add 20: true
Add 0: false
Total: 20

Here main can still write timer.minutes = 0 directly, because everything is in one module. Put Timer in its own module with a private field, as the planner does on Day 7, and the method becomes the only way in.

Start with &self

When writing a method, try &self first. Move to &mut self only if the method must change the value, and to self only if the value should be used up.

Practice

Exercise

Your turn

Add two methods to Timer, and choose the receiver of each yourself:

  • reached(goal) returns true when the timer holds at least goal minutes.
  • reset() sets the timer back to zero.

After the starter's add(20), print reached(15), then reset, then print reached(15) and total() again. The output should be 20, true, false and 0, one per line.

Your working space Rust
struct Timer {
    minutes: u32,
}

impl Timer {
    fn new() -> Self {
        Self { minutes: 0 }
    }

    fn add(&mut self, minutes: u32) {
        self.minutes += minutes;
    }

    fn total(&self) -> u32 {
        self.minutes
    }
}

fn main() {
    let mut timer = Timer::new();
    timer.add(20);
    println!("{}", timer.total());
    // Print reached(15), reset, then print reached(15) and total() again.
}
Hint 1: the idea

For each method ask one question: does it read the timer, change it, or use it up? The answer picks &self, &mut self or self, and the caller must still be able to use the timer after both calls.

Hint 2: a first step

Write reached first: it takes a goal: u32 after the receiver and returns bool, and its body is a single comparison with a field. Compare its receiver with the one total uses.

Worked solution
Run the solution Rust
struct Timer {
    minutes: u32,
}

impl Timer {
    fn new() -> Self {
        Self { minutes: 0 }
    }

    fn add(&mut self, minutes: u32) {
        self.minutes += minutes;
    }

    fn total(&self) -> u32 {
        self.minutes
    }

    fn reached(&self, goal: u32) -> bool {
        self.minutes >= goal
    }

    fn reset(&mut self) {
        self.minutes = 0;
    }
}

fn main() {
    let mut timer = Timer::new();
    timer.add(20);
    println!("{}", timer.total());
    println!("{}", timer.reached(15));
    timer.reset();
    println!("{}", timer.reached(15));
    println!("{}", timer.total());
}
Text
20
true
false
0

reached only reads a field, so it takes &self, like total. reset writes a field, so it needs &mut self. A receiver of plain self would be wrong for either: it would use the timer up, and the next call on timer would fail with E0382. If you wrote &mut self for reached, it still compiles, but the signature now claims the method may change the timer, which is more access than it needs. Next you will make the program check its own results with assertions.

Was this article helpful?

Your response is saved on this device.