// Chapter 30 example: an account whose methods guard the balance. // Run with: go run exercises/30/01-account.go package main import "fmt" type account struct { owner string balance int } func newAccount(owner string) *account { return &account{owner: owner} } func (a *account) deposit(amount int) error { if amount <= 0 { return fmt.Errorf("cannot deposit %d", amount) } a.balance = a.balance + amount return nil } func (a *account) withdraw(amount int) error { if amount <= 0 { return fmt.Errorf("cannot withdraw %d", amount) } if amount > a.balance { return fmt.Errorf("cannot withdraw %d: the balance is %d", amount, a.balance) } a.balance = a.balance - amount return nil } func (a *account) getBalance() int { return a.balance } func main() { acc := newAccount("Keiko") err := acc.deposit(100) if err != nil { fmt.Println("Error:", err) } err = acc.withdraw(30) if err != nil { fmt.Println("Error:", err) } fmt.Println(acc.getBalance()) // 70 err = acc.withdraw(1000) if err != nil { fmt.Println("Error:", err) // Error: cannot withdraw 1000: the balance is 70 } fmt.Println(acc.getBalance()) // 70 // Try this: add a method canAfford(amount int) bool that returns true when // the balance is at least amount, and use it before a withdraw. }