为了账号安全,请及时绑定邮箱和手机立即绑定

有没有更好的方法来迭代结构的字段?

有没有更好的方法来迭代结构的字段?

Go
慕后森 2022-08-01 14:45:43
我有这两个结构,我从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"`}我需要实现一个返回 和 的所有字段之和的方法,但我不确定如何将它们抽象为“具有字段的事物切片”。我当前的实现只是重复相同的代码三次:CashDepositsWithdrawalsFeesCashfunc (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}有没有更好的方法来做到这一点?
查看完整描述

2 回答

?
噜噜哒

TA贡献1784条经验 获得超7个赞

通过循环访问切片来消除重复代码:


for _, transactions := range [][]transaction{b.Deposits, b. Withdrawals, b.Fees} {

    for _, transaction := range transactions {

        if transaction.Datetime.Before(datetime) {

            cash = cash.Add(transaction.Cash)

        }

    }

}


查看完整回答
反对 回复 2022-08-01
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

您可以追加到一个数组并循环访问该数组:


func (b branch) getCash(datetime time.Time) decimal.Decimal {

    cash := decimal.NewFromFloat(0)

    arr := append(b.Deposits, b.Fees...)

    arr = append(arr, b.Withdrawals...)

    

    for _, a := range arr {

        if a.Datetime.Before(datetime) {

            cash = cash.Add(a.Cash)

        }

    }

    return cash

}


查看完整回答
反对 回复 2022-08-01
  • 2 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号