Skip to content
Exercise · Structs and methods · lesson 11 of 11

Exercise: bank account

Write the type Account, a bank account whose balance is a whole number. The constructor func NewAccount(initial int) *Account opens an account with the starting balance initial. Methods: func (a *Account) Deposit(amount int) puts money into the account, func (a *Account) Withdraw(amount int) bool takes it out and reports whether that worked, and func (a *Account) Balance() int returns the current balance.

  • NewAccount(100).Balance() → 100
  • a := NewAccount(50), then a.Withdraw(20) → true, and a.Balance() → 30
  • after that, a.Withdraw(40) → false, and a.Balance() is still 30

Constraints: amounts are non-negative; if the account holds less than amount, Withdraw returns false and leaves the balance unchanged, while withdrawing exactly the whole balance works; each account has its own balance.

Do not add extra imports unless the task says so explicitly.

account.go — go
go · 19 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way