Using Generics with Slices of Different Types in Go
Consideration of generics in Go involves the concept of core types for interfaces. An interface constraint, such as NumberSlice, has no core type since it encompasses multiple underlying types (e.g., []int64 and []float64). This poses a hindrance when attempting to iterate over slices within a generic function.
To resolve this issue, one approach is to alter the interface to mandate the base types, leaving the slice type to be determined within the function signature:
type Number interface { int64 | float64 } func add[N Number](n []N) { for _, v := range n { fmt.Println(v) } }
However, an even more thorough but verbose solution involves explicitly declaring the core type within the interface constraint:
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 that the interface has a specific underlying type ([]N) and that the function can accept and process slices of either int64 or float64.
The above is the detailed content of How Can Generics in Go Handle Slices of Different Numeric Types?. For more information, please follow other related articles on the PHP Chinese website!