Start learning free

LESSON 64 OF 69 · PROJECTS: OBJECT-ORIENTED

Bank Account in Rust: Encapsulation with a Private Balance

Practice Read the full explanation

Build a BankAccount class that keeps its balance private and lets other code change it only through methods that check the rules. This is encapsulation: the object protects its own data.

Private balance. The struct's field balance has no pub, so code outside the module cannot touch it. Methods live in an impl BankAccount block; ones that change the account take &mut self, read-only ones take &self.

What the class must have (Rust):

  • The associated function BankAccount::new(initial_balance: f64) -> BankAccount: creates an account that starts with the given balance.
  • fn deposit(&mut self, amount: f64): adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • fn withdraw(&mut self, amount: f64) -> bool: if amount is zero or negative, or larger than the balance, change nothing and return false. Otherwise subtract it from the balance and return true. Withdrawing exactly the whole balance is allowed (the balance becomes 0).
  • fn get_balance(&self) -> f64: returns the current balance. It is the only way for outside code to read it.

In Rust you also write mainFunction(), the driver, as the last steps of the lesson. println! prints the f64 value 120.0 as 120.

The driver. You write the driver last, in mainFunction(). It runs these checks:

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");
    }
}

Walk through it: start with 100, deposit 50 (150), withdraw 30 (120), withdraw 200 is refused (still 120). Then deposit -20, deposit 0 and withdraw -5 are all ignored (still 120). Withdrawing 120 succeeds and empties the account, so the balance is 0, and withdrawing 1 more is refused.

Expected output:

Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected

Both deposit and withdraw start with a guard that rejects amount <= 0. Write the guard first, then the change to the balance.

BankAccount { balance: initial_balance }

if amount <= 0.0 || amount > self.balance { return false; }, then self.balance -= amount; and true as the last expression.

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");
    }
}

STEP 1 OF 28
    Ctrl + Enter to check

    RUST · PROJECTS: OBJECT-ORIENTED

    Bank Account in Rust, explained

    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) -> bool removes money and returns true, unless the amount is zero, negative or more than the balance. In that case nothing changes and it returns false. Withdrawing the exact balance is allowed.
    • get_balance(&self) -> f64 reads 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:

    • deposit has one rule (the amount must be positive) and returns nothing.
    • withdraw has two (positive, and not more than the balance) and returns a bool, so the caller can tell whether the money left.

    Step by step

    1. Declare the struct with one field, balance: f64. In Rust the struct holds the data, and the behavior goes in a separate block.
    2. Open impl BankAccount. Every function that belongs to the type goes inside it.
    3. Write the signature of new. It has no self, so it is an associated function called as BankAccount::new(...). By convention it plays the role of a constructor.
    4. Build the struct inside new with balance set to initial_balance. This is the last expression, so it has no semicolon.
    5. Write deposit's signature. It takes &mut self because it changes the account.
    6. Write the guard if amount <= 0.0. Floats need the decimal point: 0.0, not 0.
    7. Return from the guard with return;, which ends the method before the balance is touched.
    8. Add the amount with self.balance += amount. Only a positive amount reaches this line.
    9. Write withdraw's signature: &mut self, amount, and a bool result.
    10. 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.
    11. Return false inside that if.
    12. Subtract the amount after the guard.
    13. Finish with true as the last expression, without a semicolon. Reaching this line means the withdrawal happened.
    14. Write get_balance with &self, since it only reads, and return self.balance.
    15. Write the driver. Declare mainFunction, create account with let mut, and follow the walk-through above call by call, printing with println!("Balance: {}", ...). The last two checks use the result of withdraw directly as an if condition, 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 pub can 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 touch balance. 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 self versus &self. Methods that change the account take &mut self, and get_balance takes &self. The variable also has to be declared let mut account. Without mut, calling deposit or withdraw gives error[E0596]: cannot borrow `a` as mutable, as it is not declared as mutable.
    • Printing floats. println!("{}", 120.0) prints 120, which is why the expected output has no decimal point. {:.2} would print 120.00.
    • Ignoring the result. The driver calls account.withdraw(30.0); and discards the bool. That compiles, because a bool isn'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. Writing amount >= self.balance in 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 <= 0 doesn't compile because amount is an f64. Write 0.0.
    • Floating-point rounding. An f64 can't store most decimals exactly: 0.1 + 0.2 prints 0.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 self for methods that change the value, &self for readers, and a bool result when the caller needs to know whether a request was accepted.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free