CodeBlanks Logo Icon CodeBlanks

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("...").

Practice 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.

Starter code

main.rs
struct Hesap {
    sahip: String,
    bakiye: i64,
}

fn main() {
    // buraya yaz
}

Sample solution

main.rs
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);
}

Expected output

Ok(())
Err("yetersiz bakiye: 70")
Ece: 70

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What should <code>cek</code> do when the balance is insufficient?

  • Silently do nothing
  • Return Err without touching the balance Correct answer
  • Make the balance negative
  • panic!

Explanation: A failed operation shouldn't change the state and should tell the caller why.

2 Success value

Question
self.bakiye -= tutar;
____
Answer
self.bakiye -= tutar;
Ok(())

Explanation: A success that returns no value is reported with Ok(()).

3 Method and self form

Term Meaning
Hesap::new No self
yatir &mut self
cek &mut self + Result
bakiye_goster &self

All lessons in Beginner