go - 有没有更好的方法来迭代结构的字段?
问题描述
我从 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"`
}
我需要实现一个方法来返回 和 的所有字段的总和,Cash
但Deposits
我不确定如何将它们抽象为“带有字段的事物切片”。我当前的实现只是重复相同的代码三遍:Withdrawals
Fees
Cash
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
}
有一个更好的方法吗?
解决方案
通过循环切片切片来消除重复代码:
for _, transactions := range [][]transaction{b.Deposits, b. Withdrawals, b.Fees} {
for _, transaction := range transactions {
if transaction.Datetime.Before(datetime) {
cash = cash.Add(transaction.Cash)
}
}
}
推荐阅读
- html - 如何在flexbox的两端对齐项目
- php - laravel 没有post到sql数据库没有错误
- mysql - 如何聚合原始 L3 订单数据以进行显示
- database - 如何保存对评论的回复
- coinbase-api - Coinbase Pro API 身份验证在 Python 中失败
- django - Django基于与对象的交互发送通知
- jenkins - Jenkins 没有找到新的 bitbucket 存储库
- sql - SQL 脚本在查询生成器上运行,但在执行时不运行
- terragrunt - 如何在 run-all 应用执行期间强制 Terragrunt 在第一个错误时失败
- angular - 使用 Angular 的 Google 日历创建活动