Home >Backend Development >Golang >Trying to compare two values of type V with Go generics doesn't work
php Editor Apple found that in Go language, two values of type V cannot be directly compared when using generics. This means that comparisons cannot be made simply using == or != as you can with strings or integers. This is because generics are implemented differently and cannot directly compare values. In this case, we need to use a custom comparison function or method to perform the comparison operation to achieve the functionality we require. This is a detail to pay attention to, especially when writing code involving generics.
go version: go1.21rc2
I'm writing a function in go using generics that takes a value and returns true/false if the value is in a map.
In version 1 below, I don't understand why two values cannot be compared when their type is any
? But after converting to any
in version 2, it works now... I guess I'm missing something obvious, but I don't quite understand it.
Version 1 (not working):
func invalues[m ~map[k]v, k comparable, v any](m m, v v) bool { for _, x := range maps.values(m) { if x == v { return true } } return false }
Version 2 (Working):
func InValues[M ~map[K]V, K comparable, V any](m M, v V) bool { for _, x := range maps.Values(m) { if any(x) == any(v) { return true } } return false }
V
needs to be comparable
to allow ==
.
Converting to any
then compares effectively because it uses non-generic ==
between any
, which is always allowed.
The above is the detailed content of Trying to compare two values of type V with Go generics doesn't work. For more information, please follow other related articles on the PHP Chinese website!