Boss lesson · Unit 06
A bank
Accounts, transfers and a history, with every rule a Result
What you practise
- Accounts, transfers and a history, every rule a
Result - A first design reviewed and improved
Try a question from this lesson
Pick one
A first design: taking money out returns false when it is refused. A caller gets false. What does the caller know?
struct Account { balance: i32 }
impl Account {
fn withdraw(&mut self, n: i32)
-> bool {
if n <= 0 || n > self.balance {
return false;
}
self.balance -= n;
true
}
}Correct answer
Only that it did not happen
Why
A bool has room for yes or no. Two different rules can refuse here, and the caller cannot tell them apart or show a useful message. A Result with an error enum says which rule said no.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The model
An account has a balance. A request can be refused for two reasons, and the reasons are an enum.
Every method that can be refused returns a Result. Here Ok carries the new balance, so the caller learns something useful either way.
#[derive(Debug)]
enum Deny { BadAmount, NoFunds }
struct Account { balance: i32 }
impl Account {
fn withdraw(&mut self, n: i32)
-> Result<i32, Deny> {
if n <= 0 {
return Err(Deny::BadAmount);
}
if n > self.balance {
return Err(Deny::NoFunds);
}
self.balance -= n;
Ok(self.balance)
}
}Concept
A transfer, and Ok with nothing in it
Some actions succeed with nothing to hand back. Their type is Result<(), Deny>. () is the empty value, and Ok(()) means: done, nothing to report.
A transfer is two steps that can each fail. With ? after each, the first failure ends the function and goes to the caller.
fn transfer(
from: &mut Account,
to: &mut Account,
n: i32,
) -> Result<(), Deny> {
from.withdraw(n)?;
to.deposit(n)?;
Ok(())
}Concept
A history
A bank must be able to show what happened. Each event is one of a few kinds, each with an amount: an enum again.
The account keeps a vector of entries and pushes one whenever the balance changes. The checks are left out here to keep the card short.
enum Entry { In(i32), Out(i32) }
struct Account {
balance: i32,
history: Vec<Entry>,
}
impl Account {
fn deposit(&mut self, n: i32) {
self.balance += n;
self.history.push(Entry::In(n));
}
}9 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 3× multiple choice
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.