// Chapter 30 example: package bank. Every rule about an account is here, and // other packages cannot reach past these methods to the fields. package bank import ( "errors" "fmt" ) // Account is one bank account. Make one with NewAccount. type Account struct { owner string balance int } // NewAccount returns an account with a balance of 0. The owner must not be // empty. func NewAccount(owner string) (*Account, error) { if owner == "" { return nil, errors.New("an account needs an owner") } return &Account{owner: owner}, nil } // checkAmount is a helper for this package only. func checkAmount(amount int) error { if amount <= 0 { return fmt.Errorf("the amount %d is not above 0", amount) } return nil } // Deposit adds to the balance. The amount must be above 0. func (a *Account) Deposit(amount int) error { err := checkAmount(amount) if err != nil { return err } a.balance = a.balance + amount return nil } // Withdraw takes from the balance. The amount must be above 0, and no more // than the balance. func (a *Account) Withdraw(amount int) error { err := checkAmount(amount) if err != nil { return err } if amount > a.balance { return fmt.Errorf("cannot withdraw %d: the balance is %d", amount, a.balance) } a.balance = a.balance - amount return nil } // Owner returns the name on the account. func (a *Account) Owner() string { return a.owner } // Balance returns the current balance. func (a *Account) Balance() int { return a.balance }