Scenario:
Go 1.18 that support generics
Problem:
Unable to convert a number into generics.
Explanation:
I'm trying to port my general purpose library to support generics. I'm dealing with number cast error.
I've defined a package that contains all the number types as following:
package types
type Number interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr | float32 | float64
}
I've no particular problem to deal with generics. The only thing that I've not understood is:
How to convert a defined type (like int) to a generic?
Let's assume the following example:
// FindIndexValue is delegated to retrieve the index of the given value into the input array.
func FindIndexValue[T types.Number](array []T, value T) []T {
var indexs []T
for i := range array {
if array[i] == value {
indexs = append(indexs, i)
}
}
return indexs
}
In the above snippet, the error is located in the line:
...
for i := range array {
...
}
This because the range builtin iterate the array and return the index (int) of the given position.
The question is:
How can I convert the defined type (int in this case) to the generic T?
Error:
cannot use i (variable of type int) as type T in argument to append