Defining Common Behavior for a Collection of Slices
This inquiry seeks recommendations for establishing consistent behavior among collections of slices. Consider the example of working with half open intervals. Suppose you have two types of such intervals:
Both ClockInterval and Period slices are frequently encountered in code. The challenge arises when you need to find the enclosing interval for a given time. This necessitates writing the FindEnclosingHalfOpenInterval function for both types, leading to duplicative code.
The provided code sample (https://play.golang.org/p/Cy7fFaFzYJR) demonstrates one approach, involving type conversion between slices. However, it raises questions about whether there is a more efficient way to define common behavior for multiple slice types.
Converting Slices
The appropriate method to convert a slice from one type to another is to create a new slice and iterate over the elements, converting them individually. For faster conversion, you can pre-create the resulting slice:
func ToIntervalsFromClockIntervals(clockIntervals []ClockInterval) HalfOpenIntervals { intervals := make(HalfOpenIntervals, 0, len(clockIntervals)) for _, clockInterval := range clockIntervals { intervals = append(intervals, clockInterval) } return intervals }
Composition
Alternatively, consider using composition to solve this problem. This involves creating a base struct that contains the common FindEnclosingInterval logic. For example:
type HalfOpenIntervalBase struct { intervals []HalfOpenInterval } func (base *HalfOpenIntervalBase) FindEnclosingInterval(time Time) HalfOpenInterval { // Find and return the enclosing interval using base.intervals }
You can then create separate types for ClockInterval and Period that embed this base struct:
type ClockInterval struct { HalfOpenIntervalBase } type Period struct { HalfOpenIntervalBase }
Using this approach, both ClockInterval and Period can leverage the FindEnclosingInterval functionality from the base struct, eliminating duplication.
Over-Generalization
It's important to note that over-generalization can be counterproductive. While it's tempting to pursue a universal solution that avoids code duplication, it's not always the most practical approach in Go. Duplicating code for different types is often necessary and may ultimately lead to cleaner and more maintainable code.
The above is the detailed content of How Can We Define Common Behavior for Collections of Different Slice Types in Go?. For more information, please follow other related articles on the PHP Chinese website!