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) *BankAccountcreates an account with a starting balance.deposit(amount float64)adds money, but ignores an amount that is zero or negative.withdraw(amount float64) booltakes money out and returnstrue. If the amount is zero, negative or larger than the balance, it changes nothing and returnsfalse. Withdrawing exactly the whole balance is allowed.getBalance() float64is 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
- Declare the struct.
BankAccountholds one field,balance, afloat64. - 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. - Return
&BankAccount{balance: initialBalance}. The&takes the address of the new struct. - Declare
depositon*BankAccount. The pointer receiver lets the method change the account itself instead of a copy. - Guard against bad amounts. If
amount <= 0,returnat once. - Add the amount to
this.balance. Only positive amounts reach this line. - Declare
withdraw, again on*BankAccount, with aboolresult that tells the caller whether the money left. - Refuse invalid requests. The condition is
amount <= 0 || amount > this.balanceand the body isreturn false. It uses>, not>=, so asking for exactly the balance passes. - Subtract the amount from the balance.
- Return
true: the withdrawal happened. - Declare
getBalancewith a plainBankAccountreceiver. It only reads, so a copy is enough. - Return
this.balance. - Write
mainFunctionand the driver. Createaccountwith 100, run the deposits and withdrawals described above, and print the balance three times withfmt.Printf("Balance: %d\n", int(account.getBalance())). Theifstatements use theboolfromwithdrawdirectly as their condition: one printsWithdrew allwhenwithdraw(120.0)succeeds, and one printsRejectedwhen!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.
depositandwithdrawchange the balance, so they need*BankAccount. With a value receiver they would modify a copy and the account would never change.getBalanceonly 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.
accountis a*BankAccount, andaccount.getBalance()still works: Go dereferences the pointer for you. Likewise, calling a pointer method on an addressable variable such asc := BankAccount{balance: 5}works, because Go writes(&c).deposit(10)for you. - Pointers share, values copy. If
eis a*BankAccountand you writef := e, both names point to one account: depositing 10 throughfshows 15 througheas well. With plain structs,d := ccopies the struct, so depositing intodleavescat 5. - The ignored result. The driver calls
account.withdraw(30.0)without using the returnedbool. Go allows that for function and method calls; only unused variables are errors. - Printing a
float64with%d.%dexpects an integer. Given afloat64,Printfdoesn't fail to compile, it prints a marker instead: for 10.75,fmt.Printf("%d\n", x)prints%!d(float64=10.75). Converting withint(...)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,withdrawandgetBalanceare lowercase, so within a package they are callable but another package couldn't use them. Exported names would beDeposit,Withdrawand so on, and Go style would call the getterBalance. 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'swithdraw(120.0)prints nothing. - Forgetting the
amount <= 0check onwithdraw. 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
depositorwithdraw. The code compiles and the call looks right, but the change is applied to a copy and is lost. - Floating-point rounding. A
float64can't hold most decimal fractions exactly. Ten deposits of 0.1 give 0.9999999999999999, and a withdrawal of 1.0 from that account returnsfalse. 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.
withdrawreports success. The driver uses it to printWithdrew allandRejected, 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
boolfrom an operation that can be refused, so the caller can tell what happened.
