我有一个WorkDay结构来保存某人的工作时间数据,一个WorkWeek结构来保存一堆工作日,以及一个WorkMonth结构来保存一堆工作周。想法是让每个人返回该时间段内的总工作时间。
type WorkDay struct {
StartTime time.Time
EndTime time.Time
}
type WorkWeek struct {
WorkDays []WorkDay
}
type WorkMonth struct {
WorkWeeks []WorkWeek
}
func (w WorkDay) HoursWorked() time.Duration {
// Find hours worked through simple subtraction.
}
func (w WorkWeek) HoursWorked() time.Duration {
var totalHours time.Duration
for _, day := range w.WorkDays {
totalHours += day.HoursWorked()
}
return totalHours
}
func (w WorkMonth) HoursWorked() time.Duration {
var totalHours time.Duration
for _, week := range w.WorkWeeks {
totalHours += week.HoursWorked()
}
return totalHours
}
这段代码可以正常工作,但是
WorkWeek.HoursWorked()
和WorkMonth.HoursWorked()
中的重复确实使我精疲力尽。我尝试做以下事情,以为自己很聪明:func (w WorkWeek) HoursWorked() time.Duration {
return sumHoursWorked(w.WorkDays)
}
func (m WorkMonth) HoursWorked() time.Duration {
return sumHoursWorked(m.WorkWeeks)
}
type countable interface {
HoursWorked() time.Duration
}
func sumHoursWorked(timeFrames []countable) time.Duration {
var totalHours time.Duration
for _, frame := range timeFrames {
totalHours += frame.HoursWorked()
}
return totalHours
}
但是,如here所述,即使
WorkDay
实现countable
,一片WorkDay
s也不会算作countable
s的一部分。那么,是我错过了这种巧妙的,惯用的方法吗,还是我只是坚持复制呢?
最佳答案
不。可以使用countables
的一部分,它可以为您提供动态方法分派(dispatch)或一些编程(您的第一个解决方案)或重组您的类型。我不知道您的问题范围,但包含数天的数周的月份似乎很奇怪,至少是月/周的值。