I am playing around with Go Generics in the playground, trying to write some generic array functions.
https://gotipplay.golang.org/p/vS7f_Vxxy2j
package main
import (
"fmt"
)
func array_has[T any](haystack []T, needle T) bool {
for _, val := range haystack {
if val == needle {
return true
}
}
return false
}
func main() {
arr := []string{"A","B","C"}
fmt.Println(array_has(arr, "T"))
}
The error I am getting is:
invalid operation: val == needle (type parameter T is not comparable with ==)
I can work around it by using reflect:
if reflect.ValueOf(val).Interface() == reflect.ValueOf(needle).Interface()
Go2 Playground: https://gotipplay.golang.org/p/9ZVZafQ_9JK
However, is there an (internal?) interface for "comparable" types, for which ==
is defined, that I can use instead of any
?
Are there really even types that do not support comparison with ==
?