Home >Backend Development >Golang >How to Handle Unions of Slices in Go Generic Functions?
Handling Unions of Slices in Generic Functions with Interface Constraints
Suppose you need a generic function that operates on either a slice of integers or a slice of floats. To implement this, you can utilize generics and interface constraints as demonstrated below:
package main import "fmt" // NumberSlice defines an interface for either slice of integers or slice of floats. type NumberSlice interface { []int | []float64 } // add is a generic function that iterates over a slice of NumberSlice and prints its values. func add[N NumberSlice](n N) { for _, v := range n { fmt.Println(v) } } func main() { ints := []int{1, 2} add(ints) floats := []float64{3.14, 1.618} add(floats) }
However, when attempting to run the above code, you may encounter the following error:
cannot range over n (variable of type N constrained by NumberSlice) (N has no core type)
This error arises because the NumberSlice interface does not have a core type. A core type for an interface is a single underlying type that all types in the interface must inherit. Since NumberSlice can accept both slices of integers and slices of floats, it does not meet this requirement.
To address this issue, you can define the interface using the base types instead of slices:
type Number interface { int | float64 } func add[N Number](n []N) { for _, v := range n { fmt.Println(v) } }
This modified function takes a slice of Number elements as a parameter, allowing it to handle both integers and floats efficiently.
The above is the detailed content of How to Handle Unions of Slices in Go Generic Functions?. For more information, please follow other related articles on the PHP Chinese website!