2017-01-06 6 views
1

私は以下のドメインを持っています。 1つのアカウントから別のアカウントにamountを転送できるTransfer機能を実装するにはどうすればよいですか。私は貯蓄から小切手への移行が可能でなければなりません。私は世界を愛する、スーパータイプはそれをより簡単にする。私はGoでこれをどのように達成するのだろうかと思っています。練習としてGolang:転送方法/機能の実装方法

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 
} 

答えて

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されたインタフェースを設計する価値があるかもしれません。

+0

ですので、関数にする必要があります。私はそれをメソッドとして実装しようとしていました。つまり、TransferはAccountインターフェイスタイプの一部です。 –

+0

https://play.golang.org/p/MC11OPJR3j解決策にエラーが発生しました –

+0

@ AravindR.Yarram:構造体へのポインタを渡します。https://play.golang.org/p/dvBRS7xzQN –

関連する問題