我有这两个结构,我从JSON文件填充:
type transaction struct {
Datetime time.Time `json:"datetime"`
Desc string `json:"desc"`
Cash decimal.Decimal `json:"cash"`
}
type branch struct {
BranchName string `json:"branch-name"`
Currency string `json:"currency"`
Deposits []transaction `json:"deposits"`
Withdrawals []transaction `json:"withdrawals"`
Fees []transaction `json:"fees"`
}
我需要实现一个返回 和 的所有字段之和的方法,但我不确定如何将它们抽象为“具有字段的事物切片”。我当前的实现只是重复相同的代码三次:CashDepositsWithdrawalsFeesCash
func (b branch) getCash(datetime time.Time) decimal.Decimal {
cash := decimal.NewFromFloat(0)
for _, deposit := range b.Deposits {
if deposit.Datetime.Before(datetime) {
cash = cash.Add(deposit.Cash)
}
}
for _, withdrawal := range b.Withdrawals {
if withdrawal.Datetime.Before(datetime) {
cash = cash.Add(withdrawal.Cash)
}
}
for _, fee := range b.Fees {
if fee.Datetime.Before(datetime) {
cash = cash.Add(fee.Cash)
}
}
return cash
}
有没有更好的方法来做到这一点?
噜噜哒
慕桂英546537
相关分类