Rust
Bank account
Model a simple bank with an Account struct and methods.
Final task: bank account
Model a bank account with a struct and methods. Depositing always succeeds; withdrawing must fail if the balance is insufficient and report this with Result:
struct Hesap {
sahip: String,
bakiye: i64,
}
impl Hesap {
fn new(sahip: &str) -> Self { /* balance 0 */ }
fn yatir(&mut self, tutar: i64) { /* ... */ }
fn cek(&mut self, tutar: i64) -> Result<(), String> { /* ... */ }
}
Result<(), String>: on success there's no value to return (()), on error there's a description.
Checking with an early return
Handling the error case first and returning early keeps the main logic simple:
fn cek(&mut self, tutar: i64) -> Result<(), String> {
if tutar > self.bakiye {
return Err(format!("yetersiz bakiye: {}", self.bakiye));
}
self.bakiye -= tutar;
Ok(())
}
When printed with {:?}, success appears as Ok(()) and an error as Err("...").
Exercise Account operations
Write the Hesap struct above and the methods new, yatir and cek. Open an account for "Ece" and deposit 100; print the results of cek(30) and cek(500) with {:?} on separate lines, and finally Ece: 70.
Show example solution
struct Hesap {
sahip: String,
bakiye: i64,
}
impl Hesap {
fn new(sahip: &str) -> Self {
Self {
sahip: sahip.to_string(),
bakiye: 0,
}
}
fn yatir(&mut self, tutar: i64) {
self.bakiye += tutar;
}
fn cek(&mut self, tutar: i64) -> Result<(), String> {
if tutar > self.bakiye {
return Err(format!("yetersiz bakiye: {}", self.bakiye));
}
self.bakiye -= tutar;
Ok(())
}
}
fn main() {
let mut h = Hesap::new("Ece");
h.yatir(100);
println!("{:?}", h.cek(30));
println!("{:?}", h.cek(500));
println!("{}: {}", h.sahip, h.bakiye);
}
Test yourself
-
What should <code>cek</code> do when the balance is insufficient?
- Silently do nothing
- Return Err without touching the balance
- Make the balance negative
- panic!
Show answer
Return Err without touching the balance — A failed operation shouldn't change the state and should tell the caller why.
-
Success value
self.bakiye -= tutar;
____
Show answer
self.bakiye -= tutar;
Ok(())
-
Method and self form
- Hesap::new
- No self
- yatir
- &mut self
- cek
- &mut self + Result
- bakiye_goster
- &self
Next lesson: Temperature converter