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?
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
Total: 20add 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:
&selfreads the value. The caller keeps it, and many reads can happen one after another.&mut selfchanges the value. The caller's binding must bemut.selftakes 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.
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}");
}Methods took 25 minformat! 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.
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);
}Add 20: true
Add 0: false
Total: 20Here 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
Your turn
Add two methods to Timer, and choose the receiver of each yourself:
reached(goal)returnstruewhen the timer holds at leastgoalminutes.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.
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
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());
}20
true
false
0reached 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.
Completion is saved in this browser only. It does not measure mastery.