Iterating Over a Union of Slices in a Generic Function Without a Core Type
In Go 1.18, generic functions allow us to work with types dynamically. However, encountering challenges in iterating over a slice composed of varying types requires additional considerations.
When dealing with type constraints, we must understand the concept of a core type. A core type exists when a single underlying type exists for all types in an interface or when all channels have the same element type and direction.
In the initial code example:
type NumberSlice interface { []int64 | []float64 }
The interface constraint NumberSlice does not have a core type because it comprises multiple underlying types: []int64 and []float64. This means we cannot range over slices of this interface.
To overcome this obstacle, we can modify the interface to require the base types instead:
type Number interface { int64 | float64 } func add[N Number](n []N) { for _, v := range n { fmt.Println(v) } }
This allows us to declare slices of int64 or float64 and iterate over them within the generic function.
Alternatively, we can define a more explicit interface with a core type:
type NumberSlice[N int64 | float64] interface { ~[]N } func add[S NumberSlice[N], N int64 | float64](n S) { for _, v := range n { fmt.Println(v) } }
This approach ensures the interface has a known underlying type of []N for all types implementing NumberSlice[N].
By making these adjustments, we can successfully iterate over unions of slices within generic functions, providing increased flexibility in our code.
The above is the detailed content of How Can I Iterate Over a Union of Slices in a Go Generic Function Without a Core Type?. For more information, please follow other related articles on the PHP Chinese website!