我有以下域名。我们如何实施Transfer
功能,将amount
从一个帐户转移到另一个帐户。我应该可以从储蓄转移到检查,反之亦然。我是OOP世界,超级型更容易。我想知道我们如何在Go中实现这一目标。
type AccountData struct {
Num string
Name string
OpenDate time.Time
Balance float64
}
type SavingsAccount struct {
InterestRate float32
AccountData
}
type CheckingAccount struct {
TransactionFee float32
AccountData
}
type Account interface {
Deposit(amount float64) error
Withdraw(amount float64) error
}
//constructor functions
func OpenSavingsAccount(no string, name string, openingDate time.Time) SavingsAccount {
return SavingsAccount{
AccountData: AccountData{Num: no,
Name: name,
OpenDate: openingDate,
},
InterestRate: 0.9,
}
}
func OpenCheckingAccount(no string, name string, openingDate time.Time) CheckingAccount {
return CheckingAccount{
AccountData: AccountData{Num: no,
Name: name,
OpenDate: openingDate,
},
TransactionFee: 0.15,
}
}
//Account methods
func (acct *SavingsAccount) Withdraw(amount float64) error {
if acct.Balance < amount {
return errors.New("Not enough money to withdraw")
}
acct.Balance = acct.Balance - amount
return nil
}
func (acct *SavingsAccount) Deposit(amount float64) error {
fmt.Printf("Depositing %f \n", amount)
acct.Balance = acct.Balance + amount
return nil
}
func (acct *CheckingAccount) Deposit(amount float64) error {
fmt.Printf("Depositing %f \n", amount)
acct.Balance = acct.Balance + amount
return nil
}
func (acct *CheckingAccount) Withdraw(amount float64) error {
if acct.Balance < amount {
return errors.New("Not enough money to withdraw")
}
acct.Balance = acct.Balance - amount
return nil
}
答案 0 :(得分:3)
func Transfer(to, from Account, amount float64) error {
if err := from.Withdraw(amount); err != nil {
return err
}
if err := to.Deposit(amount); err != nil {
if err := from.Deposit(amount); err != nil {
// `from` should be alerted that their money
// just vanished into thin air
}
return err
}
return nil
}
作为练习,设计一个交易为atomic的界面可能是值得的。