英文:
Attempting to compare two values of type V with Go generics not working
问题
Go版本:go1.21rc2
我正在使用Go中的泛型编写一个函数,该函数接受一个值,并在映射中返回true/false,以指示该值是否存在。
在下面的第一个版本中,我不明白为什么当它们的类型为any时,这两个值不能进行比较?但是在第二个版本中,将它们转换为any类型后,它现在可以工作了...我猜我可能错过了一些明显的东西,但我真的不太理解这个。
版本1(不工作):
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
}
版本2(工作):
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
}
英文:
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
}
答案1
得分: 3
V需要是可比较的,才能允许使用==。将其转换为any类型,然后进行比较是有效的,因为这样可以使用非泛型的==操作符,而对于any类型,这种比较总是被允许的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论