Optimizing Code for Common Collection Slice Behavior
In the context of working with collections of half-open intervals, such as clocks and periods, a primary concern is finding the enclosing interval for a given time for both types of intervals. This repetitive task calls for an efficient way to define common behavior for these collections.
Conversion Considerations
One approach involves converting one type of slice into another. However, the recommended method is to create a new slice and convert each item explicitly. For instance, to convert a slice of ClockIntervals into HalfOpenIntervals:
func ToIntervalsFromClockIntervals(clockIntervals []ClockInterval) HalfOpenIntervals { intervals := make(HalfOpenIntervals, 0, len(clockIntervals)) for _, clockInterval := range clockIntervals { intervals = append(intervals, clockInterval) } return intervals }
Leveraging Composition
An alternative approach is to utilize composition to avoid重复代码。创建基础结构BasicInterval,它包含排序和GetEnclosingInterval函数的实现。ClockIntervals和PeriodIntervals则继承BasicInterval并拥有指向内部slice的便捷方法。
Avoiding Overgeneralization
It's important to note that overly generalizing can introduce complexity and reduce code readability in Go. In some cases, it may be more pragmatic to accept some duplication of code for different types. This approach can often lead to cleaner, more maintainable code in the long run.
以上是我们如何优化 Go 代码以查找不同集合类型中的封闭区间?的详细内容。更多信息请关注PHP中文网其他相关文章!