Problem overview
You build a BankAccount type whose balance can't be changed directly. Other code has to go through methods, and the methods enforce the rules. This is encapsulation: the object protects its own data.
The type needs four members:
BankAccount::new(initial_balance: f64)creates an account with a starting balance.deposit(&mut self, amount: f64)adds money. A zero or negative amount does nothing.withdraw(&mut self, amount: f64) -> boolremoves money and returnstrue, unless the amount is zero, negative or more than the balance. In that case nothing changes and it returnsfalse. Withdrawing the exact balance is allowed.get_balance(&self) -> f64reads the balance.
The last steps of the lesson are a driver in mainFunction. It starts with 100, deposits 50 (150), withdraws 30 (120) and tries to withdraw 200, which is refused. It then tries a deposit of -20, a deposit of 0 and a withdrawal of -5, all ignored, and prints the balance. A withdrawal of 120 succeeds and empties the account, and a final withdrawal of 1 is refused. The expected output is:
Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected
Approach: guard first, then change
Both deposit and withdraw follow the same shape: check whether the request is valid, leave early if it isn't, and only then touch the balance. Because every change goes through these methods, the balance can never become invalid through them. The rules live in one place, so no other code has to remember them.
The differences are small:
deposithas one rule (the amount must be positive) and returns nothing.withdrawhas two (positive, and not more than the balance) and returns abool, so the caller can tell whether the money left.
Step by step
- Declare the struct with one field,
balance: f64. In Rust the struct holds the data, and the behavior goes in a separate block. - Open
impl BankAccount. Every function that belongs to the type goes inside it. - Write the signature of
new. It has noself, so it is an associated function called asBankAccount::new(...). By convention it plays the role of a constructor. - Build the struct inside
newwithbalanceset toinitial_balance. This is the last expression, so it has no semicolon. - Write
deposit's signature. It takes&mut selfbecause it changes the account. - Write the guard
if amount <= 0.0. Floats need the decimal point:0.0, not0. - Return from the guard with
return;, which ends the method before the balance is touched. - Add the amount with
self.balance += amount. Only a positive amount reaches this line. - Write
withdraw's signature:&mut self,amount, and aboolresult. - Write the refusal condition: the amount is not positive, or it is larger than the balance. Because the test is
>and not>=, taking the whole balance passes. - Return
falseinside thatif. - Subtract the amount after the guard.
- Finish with
trueas the last expression, without a semicolon. Reaching this line means the withdrawal happened. - Write
get_balancewith&self, since it only reads, and returnself.balance. - Write the driver. Declare
mainFunction, createaccountwithlet mut, and follow the walk-through above call by call, printing withprintln!("Balance: {}", ...). The last two checks use the result ofwithdrawdirectly as anifcondition, and!in front of the call to run the body when the withdrawal was refused.
The solution in Rust
struct BankAccount {
balance: f64,
}
impl BankAccount {
fn new(initial_balance: f64) -> BankAccount {
BankAccount {
balance: initial_balance,
}
}
fn deposit(&mut self, amount: f64) {
if amount <= 0.0 {
return;
}
self.balance += amount;
}
fn withdraw(&mut self, amount: f64) -> bool {
if amount <= 0.0 || amount > self.balance {
return false;
}
self.balance -= amount;
true
}
fn get_balance(&self) -> f64 {
self.balance
}
}
fn mainFunction() {
let mut account = BankAccount::new(100.0);
account.deposit(50.0);
account.withdraw(30.0);
account.withdraw(200.0);
println!("Balance: {}", account.get_balance());
account.deposit(-20.0);
account.deposit(0.0);
account.withdraw(-5.0);
println!("Balance: {}", account.get_balance());
if account.withdraw(120.0) {
println!("Withdrew all");
}
println!("Balance: {}", account.get_balance());
if !account.withdraw(1.0) {
println!("Rejected");
}
}
Language details
- Privacy in Rust is per module. A field without
pubcan be read and written only by code in the same module. In a single-file program everything shares one module, so the lesson's driver could technically touchbalance. Inside a module of its own, outside code can't:
mod bank {
pub struct BankAccount { balance: f64 }
impl BankAccount {
pub fn new(b: f64) -> BankAccount { BankAccount { balance: b } }
}
}
fn main() {
let mut a = bank::BankAccount::new(100.0);
a.balance = 1000000.0;
}
The compiler rejects the assignment with error[E0616]: field `balance` of struct `BankAccount` is private. Methods marked pub are then the only way in.
&mut selfversus&self. Methods that change the account take&mut self, andget_balancetakes&self. The variable also has to be declaredlet mut account. Withoutmut, callingdepositorwithdrawgiveserror[E0596]: cannot borrow `a` as mutable, as it is not declared as mutable.- Printing floats.
println!("{}", 120.0)prints120, which is why the expected output has no decimal point.{:.2}would print120.00. - Ignoring the result. The driver calls
account.withdraw(30.0);and discards thebool. That compiles, because aboolisn't marked as one that must be used.
Edge cases and common mistakes
- Withdrawing exactly the balance.
withdraw(120.0)on a balance of 120 must succeed and leave 0. Writingamount >= self.balancein the guard would wrongly refuse it. - Zero and negative amounts. A negative deposit would silently lower the balance, and a negative withdrawal would raise it. The guards stop both.
- Changing the balance before checking. The check has to come first. Subtracting and then testing would leave a changed balance behind after a refusal.
- Integer literals for floats.
amount <= 0doesn't compile becauseamountis anf64. Write0.0. - Floating-point rounding. An
f64can't store most decimals exactly:0.1 + 0.2prints0.30000000000000004. The lesson uses whole numbers, so the output is exact, but the same code with fractional amounts can show tiny errors.
Key takeaways
- Keep fields private and expose methods that check the rules.
- Validate first and change state afterwards, returning early when the request is invalid.
- Use
&mut selffor methods that change the value,&selffor readers, and aboolresult when the caller needs to know whether a request was accepted.
