Home >Backend Development >Golang >How to Iterate Over a Union of Slices in Go Generic Functions?
Iterating Over a Union of Slices in Generic Functions
Generics in Go allow functions to operate on a range of types, enabling code reuse and type safety. However, when working with slices of different element types, there may be challenges when iterating over them within generic functions.
Consider the following example that aims to sum up elements of a slice, potentially containing either integers or floats:
package main import "fmt" // NumberSlice constraint type NumberSlice interface { []int64 | []float64 } func add[N NumberSlice](n N) { // want: to range over n and print value of v for _, v := range n { fmt.Println(v) } } func main() { ints := []int64{1, 2} add(ints) }
When running this code, the following error occurs:
cannot range over n (variable of type N constrained by NumberSlice) (N has no core type)
The issue lies in the lack of a "core type" for the NumberSlice interface constraint. A core type represents a single underlying type shared by all types in the interface's type set. Since NumberSlice encompasses both []int64 and []float64, it has no core type.
To resolve this issue, there are a few approaches:
Enforce a Common Base Type:
Modify the interface constraint to specify the base types and stipulate the slice type within the function signature:
type Number interface { int64 | float64 } func add[N Number](n []N) { for _, v := range n { fmt.Println(v) } }
Use Generics with Explicit Typing:
Declare a generic slice type that specifies the element type and use explicit typing to indicate the desired element type:
type NumberSlice[N int64 | float64] interface { ~[]N // indicates a core type of []N } func add[S NumberSlice[N], N int64 | float64](n S) { for _, v := range n { fmt.Println(v) } }
By specifying a core type, the compiler can infer the appropriate iteration behavior, enabling the desired operation of iterating over the slice within the generic function.
The above is the detailed content of How to Iterate Over a Union of Slices in Go Generic Functions?. For more information, please follow other related articles on the PHP Chinese website!