// Package account handles bank accounts.
package account
import "sync"
// Account represents a bank account.
type Account struct {
open bool
balance int
sync.Mutex
}
// Open return a new Account, with initial balance as a parameter.
func Open(initial int) *Account {
if initial < 0 {
return nil
}
return &Account{
open: true,
balance: initial,
}
}
// Balance returns the balance of an open Account.
func (acc *Account) Balance() (int, bool) {
if !acc.open {
return 0, false
}
return acc.balance, true
}
// Close closes the Account. Forbids further deposits.
func (acc *Account) Close() (int, bool) {
acc.Lock()
if !acc.open {
acc.Unlock()
return 0, false
}
acc.open = false
acc.Unlock()
return acc.balance, true
}
// Deposit makes a transaction on the Account.
func (acc *Account) Deposit(amount int) (int, bool) {
acc.Lock()
if !acc.open || amount < 0 && -amount > acc.balance {
acc.Unlock()
return 0, false
}
acc.balance += amount
acc.Unlock()
return acc.balance, true
}