0

Go version: go1.21rc2

I'm writing a function using generics in Go, that takes a value and returns true/false if the value is in the map.

In version 1 below, I don't understand why the two values can't be compared when they're of type any? But after casting to type any in version 2, it now works... I assume I've missed something obvious but I don't really understand this.

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
}
Sam Wood
  • 327
  • 3
  • 17
  • Your second version _compiles_ and works for _some_ cases because interface values are comparable but probably isn't what you _want_. You basically cannot use any as constraint for V (you have to use comparable) and even then your code will be broken unless you _really_ do some hard work to make it correct (e.g. for float64). – Volker Jul 02 '23 at 08:53

1 Answers1

3

V needs to be comparable for == to be allowed.
The cast to any and then comparison works because then it uses the non generic == between any which is always allowed.

Daniel
  • 30,896
  • 18
  • 85
  • 139