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()→100a := NewAccount(50), thena.Withdraw(20)→true, anda.Balance()→30- after that,
a.Withdraw(40)→false, anda.Balance()is still30
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.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.