Start learning free

LESSON 64 OF 69 · PROJECTS: OBJECT-ORIENTED

Bank Account in Go: 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. Go has no private keyword: a name that starts with a lowercase letter, like the field balance, is visible only inside its package. Methods are declared outside the struct with a receiver, func (this *BankAccount) ....

What the class must have (Go):

  • The constructor function NewBankAccount(initialBalance float64) *BankAccount: creates an account that starts with the given balance.
  • func (this *BankAccount) deposit(amount float64): adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • func (this *BankAccount) withdraw(amount float64) 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).
  • func (this BankAccount) getBalance() float64: returns the current balance. It is the only way for outside code to read it.

In Go you also write mainFunction(), the driver, as the last steps of the lesson. It prints the balance with %d and int(...).

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

func mainFunction() {
    account := NewBankAccount(100.0)
    account.deposit(50.0)
    account.withdraw(30.0)
    account.withdraw(200.0)
    fmt.Printf("Balance: %d\n", int(account.getBalance()))
    account.deposit(-20.0)
    account.deposit(0.0)
    account.withdraw(-5.0)
    fmt.Printf("Balance: %d\n", int(account.getBalance()))
    if account.withdraw(120.0) {
        fmt.Println("Withdrew all")
    }
    fmt.Printf("Balance: %d\n", int(account.getBalance()))
    if !account.withdraw(1.0) {
        fmt.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.

return &BankAccount{balance: initialBalance}

if amount <= 0 || amount > this.balance { return false }, then this.balance -= amount and return true.

type BankAccount struct {
    balance float64
}

func NewBankAccount(initialBalance float64) *BankAccount {
    return &BankAccount{balance: initialBalance}
}

func (this *BankAccount) deposit(amount float64) {
    if amount <= 0 {
        return
    }
    this.balance += amount
}

func (this *BankAccount) withdraw(amount float64) bool {
    if amount <= 0 || amount > this.balance {
        return false
    }
    this.balance -= amount
    return true
}

func (this BankAccount) getBalance() float64 {
    return this.balance
}



func mainFunction() {
    account := NewBankAccount(100.0)
    account.deposit(50.0)
    account.withdraw(30.0)
    account.withdraw(200.0)
    fmt.Printf("Balance: %d\n", int(account.getBalance()))
    account.deposit(-20.0)
    account.deposit(0.0)
    account.withdraw(-5.0)
    fmt.Printf("Balance: %d\n", int(account.getBalance()))
    if account.withdraw(120.0) {
        fmt.Println("Withdrew all")
    }
    fmt.Printf("Balance: %d\n", int(account.getBalance()))
    if !account.withdraw(1.0) {
        fmt.Println("Rejected")
    }
}

STEP 1 OF 25
    Ctrl + Enter to check

    GO · PROJECTS: OBJECT-ORIENTED

    Bank Account in Go, explained

    Problem overview

    The lesson builds a BankAccount type that guards its own money. Outside code can't set the balance to whatever it likes. It has to go through methods that check the rules:

    • NewBankAccount(initialBalance float64) *BankAccount creates an account with a starting balance.
    • deposit(amount float64) adds money, but ignores an amount that is zero or negative.
    • withdraw(amount float64) bool takes money out and returns true. If the amount is zero, negative or larger than the balance, it changes nothing and returns false. Withdrawing exactly the whole balance is allowed.
    • getBalance() float64 is the only way to read the balance.

    The last steps of the lesson are a driver, mainFunction. Starting from 100, it deposits 50 and withdraws 30, which leaves 120. A withdrawal of 200 is refused, so the balance stays 120. A deposit of -20, a deposit of 0 and a withdrawal of -5 are all ignored. Withdrawing 120 succeeds and empties the account, and one more withdrawal of 1 is refused.

    Approach: validate in the methods

    Encapsulation means the data is hidden and the methods are the only door. Every rule lives in exactly one place, so no caller can break it by accident.

    Go has no private keyword. Visibility depends on the first letter of a name. A lowercase name such as balance is visible only inside its own package, and an uppercase one would be exported to every package. So balance is hidden from other packages. Code inside the same package can still touch it, so this is a convention-plus-compiler boundary, not a per-type lock.

    Each method then follows the same pattern: check the bad cases first and leave early, then do the real work. Guards at the top keep the main path short and make it clear which inputs are rejected.

    Step by step

    1. Declare the struct. BankAccount holds one field, balance, a float64.
    2. Write the constructor. Go has no constructors, so by convention a function named New... builds the value. It returns a *BankAccount, a pointer, so every caller works on the same account.
    3. Return &BankAccount{balance: initialBalance}. The & takes the address of the new struct.
    4. Declare deposit on *BankAccount. The pointer receiver lets the method change the account itself instead of a copy.
    5. Guard against bad amounts. If amount <= 0, return at once.
    6. Add the amount to this.balance. Only positive amounts reach this line.
    7. Declare withdraw, again on *BankAccount, with a bool result that tells the caller whether the money left.
    8. Refuse invalid requests. The condition is amount <= 0 || amount > this.balance and the body is return false. It uses >, not >=, so asking for exactly the balance passes.
    9. Subtract the amount from the balance.
    10. Return true: the withdrawal happened.
    11. Declare getBalance with a plain BankAccount receiver. It only reads, so a copy is enough.
    12. Return this.balance.
    13. Write mainFunction and the driver. Create account with 100, run the deposits and withdrawals described above, and print the balance three times with fmt.Printf("Balance: %d\n", int(account.getBalance())). The if statements use the bool from withdraw directly as their condition: one prints Withdrew all when withdraw(120.0) succeeds, and one prints Rejected when !account.withdraw(1.0) is true.

    The solution in Go

    type BankAccount struct {
        balance float64
    }
    
    func NewBankAccount(initialBalance float64) *BankAccount {
        return &BankAccount{balance: initialBalance}
    }
    
    func (this *BankAccount) deposit(amount float64) {
        if amount <= 0 {
            return
        }
        this.balance += amount
    }
    
    func (this *BankAccount) withdraw(amount float64) bool {
        if amount <= 0 || amount > this.balance {
            return false
        }
        this.balance -= amount
        return true
    }
    
    func (this BankAccount) getBalance() float64 {
        return this.balance
    }
    
    
    
    func mainFunction() {
        account := NewBankAccount(100.0)
        account.deposit(50.0)
        account.withdraw(30.0)
        account.withdraw(200.0)
        fmt.Printf("Balance: %d\n", int(account.getBalance()))
        account.deposit(-20.0)
        account.deposit(0.0)
        account.withdraw(-5.0)
        fmt.Printf("Balance: %d\n", int(account.getBalance()))
        if account.withdraw(120.0) {
            fmt.Println("Withdrew all")
        }
        fmt.Printf("Balance: %d\n", int(account.getBalance()))
        if !account.withdraw(1.0) {
            fmt.Println("Rejected")
        }
    }
    

    Running the driver prints:

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

    The Go details worth knowing:

    • Pointer and value receivers. deposit and withdraw change the balance, so they need *BankAccount. With a value receiver they would modify a copy and the account would never change. getBalance only reads, so a value receiver works. Mixing the two kinds on one type is legal, and the lesson does it to show the difference, although many Go programmers prefer to use pointer receivers throughout once any method needs one.
    • Calling through the pointer. account is a *BankAccount, and account.getBalance() still works: Go dereferences the pointer for you. Likewise, calling a pointer method on an addressable variable such as c := BankAccount{balance: 5} works, because Go writes (&c).deposit(10) for you.
    • Pointers share, values copy. If e is a *BankAccount and you write f := e, both names point to one account: depositing 10 through f shows 15 through e as well. With plain structs, d := c copies the struct, so depositing into d leaves c at 5.
    • The ignored result. The driver calls account.withdraw(30.0) without using the returned bool. Go allows that for function and method calls; only unused variables are errors.
    • Printing a float64 with %d. %d expects an integer. Given a float64, Printf doesn't fail to compile, it prints a marker instead: for 10.75, fmt.Printf("%d\n", x) prints %!d(float64=10.75). Converting with int(...) first fixes that, and the conversion truncates toward zero, so 10.75 becomes 10. The lesson's balances are whole numbers, so nothing is lost. To see cents, use %.2f.
    • The lowercase names. deposit, withdraw and getBalance are lowercase, so within a package they are callable but another package couldn't use them. Exported names would be Deposit, Withdraw and so on, and Go style would call the getter Balance. The lesson keeps the lowercase names, and your code must too.

    Edge cases and common mistakes

    • Using >= in the withdraw guard. Then withdrawing exactly the balance is refused, and the driver's withdraw(120.0) prints nothing.
    • Forgetting the amount <= 0 check on withdraw. A withdrawal of -5 would pass the "too large" test and then increase the balance, because subtracting a negative adds.
    • Checking only amount < 0. Zero is also rejected for deposits and withdrawals, so use <= 0.
    • Changing the balance before checking. Validate first, then modify. A refused call must leave the balance exactly as it was.
    • A value receiver on deposit or withdraw. The code compiles and the call looks right, but the change is applied to a copy and is lost.
    • Floating-point rounding. A float64 can't hold most decimal fractions exactly. Ten deposits of 0.1 give 0.9999999999999999, and a withdrawal of 1.0 from that account returns false. Real money code usually stores whole cents in an integer for this reason. The lesson uses whole amounts, so it isn't affected.
    • Ignoring the return value when it matters. withdraw reports success. The driver uses it to print Withdrew all and Rejected, and real callers should check it before handing out money.

    Key takeaways

    • Lowercase field names keep data out of other packages; methods become the controlled way in.
    • Put the rule checks at the top of each method and return early.
    • Methods that change the struct need a pointer receiver; read-only methods can use a value receiver.
    • Return a bool from an operation that can be refused, so the caller can tell what happened.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free