A book in the queue starts as pending and can be finished once. If any code could write status = Status::Finished, finishing an already finished book would silently succeed, and nothing would tell the user they typed the wrong ID. A better design puts the rule in one method. The method decides which states may follow which, changes the value only when the move is allowed, and reports a rejection the caller cannot overlook.
The method takes &mut self, because it may change the status in place, and returns Result<(), FinishError>. Ok(()) means "done, nothing to hand back". Err(...) carries the reason. #[derive(Debug, PartialEq, Eq)] asks Rust to generate debug formatting and equality, so a check can compare outcomes with assert_eq!. A dedicated error enum, rather than a message string, lets a caller compare the reason without depending on its wording.
Predict and run
What does each call return? What is stored after the second one?
#[derive(Debug, PartialEq, Eq)]
enum FinishError {
AlreadyFinished,
}
#[derive(Debug)]
enum Status {
Pending,
Finished,
}
impl Status {
fn finish(&mut self) -> Result<(), FinishError> {
match self {
Self::Pending => {
*self = Self::Finished;
Ok(())
}
Self::Finished => Err(FinishError::AlreadyFinished),
}
}
}
fn main() {
let mut status = Status::Pending;
println!("{:?}", status.finish());
println!("{:?}", status.finish());
println!("{status:?}");
}Check your prediction
Ok(())
Err(AlreadyFinished)
FinishedThe first call finds Pending and replaces it. The second finds Finished and returns an error without touching anything, so the stored status is still Finished. Change the starting value to Status::Finished and predict both calls before you run.
Writing through the mutable borrow
Inside the method, self is a &mut Status, a reference. *self = Self::Finished; writes a new value into the place the reference points at, which is the caller's status. Forgetting the star is a common slip:
Self::Pending => {
self = Self::Finished;
Ok(())
}It fails with error[E0308]: mismatched types, noting "expected &mut Status, found Status". You do not want to point self somewhere else; you want to change what it points at.
Two more details. Self means the type being implemented, so Self::Pending is Status::Pending. And because Result is marked #[must_use], a caller who writes status.finish(); and ignores the result gets a warning: unused Result that must be used. Rejections are hard to lose by accident.
Transitions that carry data
Real states often carry data, and a method can update it in place. Here a book can also be in progress at a given page. Reading forward is allowed, reading backward is not, and a finished book cannot be read again.
#[derive(Debug, PartialEq, Eq)]
enum ReadError {
Backward { at: u32 },
AlreadyFinished,
}
#[derive(Debug)]
enum Status {
Pending,
Reading { page: u32 },
Finished,
}
impl Status {
fn read_to(&mut self, target: u32) -> Result<(), ReadError> {
match self {
Self::Pending => *self = Self::Reading { page: target },
Self::Reading { page } if target < *page => {
return Err(ReadError::Backward { at: *page });
}
Self::Reading { page } => *page = target,
Self::Finished => return Err(ReadError::AlreadyFinished),
}
Ok(())
}
}
fn main() {
let mut status = Status::Pending;
for target in [40, 25, 90] {
let result = status.read_to(target);
println!("{target}: {result:?} -> {status:?}");
}
status = Status::Finished;
println!("{:?}", status.read_to(10));
}40: Ok(()) -> Reading { page: 40 }
25: Err(Backward { at: 40 }) -> Reading { page: 40 }
90: Ok(()) -> Reading { page: 90 }
Err(AlreadyFinished)Matching on self gives page the type &mut u32, so *page = target updates the number inside the variant without rebuilding it. The arm if target < *page is a match guard: it only applies when the condition holds, and otherwise the next arm is tried. The rejected move left the page at 40, which is the property worth checking: a failed call changes nothing. The error variant also carries the current page, so the caller can explain the rejection.
Check the state after a rejection
When you test a transition, assert both the returned error and the stored state afterward. A method that returns the right error but has already changed the value is a bug that the error alone will not show.
Practice
Your turn
Implement shelve(&mut self) -> Result<(), ShelfError> on State. Only a checked-out item can be shelved. Assert that the first call succeeds, the second returns Err(ShelfError::AlreadyOnShelf), and the item is still OnShelf after the rejection. Print Shelf checks passed at the end.
#[derive(Debug, PartialEq, Eq)]
enum State {
CheckedOut,
OnShelf,
}
#[derive(Debug, PartialEq, Eq)]
enum ShelfError {
AlreadyOnShelf,
}
fn main() {
let mut state = State::CheckedOut;
// Call shelve twice and check the final state.
println!("{state:?}");
}Hint 1: the idea
Handle the two states in separate arms. Only the CheckedOut arm should assign through self.
Hint 2: a first step
Add impl State { fn shelve(&mut self) -> Result<(), ShelfError> { match self { ... } } }, and remember the star in *self = Self::OnShelf;.
Worked solution
#[derive(Debug, PartialEq, Eq)]
enum State {
CheckedOut,
OnShelf,
}
#[derive(Debug, PartialEq, Eq)]
enum ShelfError {
AlreadyOnShelf,
}
impl State {
fn shelve(&mut self) -> Result<(), ShelfError> {
match self {
Self::CheckedOut => {
*self = Self::OnShelf;
Ok(())
}
Self::OnShelf => Err(ShelfError::AlreadyOnShelf),
}
}
}
fn main() {
let mut state = State::CheckedOut;
assert_eq!(state.shelve(), Ok(()));
assert_eq!(state.shelve(), Err(ShelfError::AlreadyOnShelf));
assert_eq!(state, State::OnShelf);
println!("Shelf checks passed");
}Shelf checks passedThe third assertion checks the state after the rejection, not only the returned error. assert_eq! needs PartialEq to compare and Debug to print both sides if they differ, which is why both enums derive them. The checkpoint combines this kind of method with a private constructor.
Completion is saved in this browser only. It does not measure mastery.