尝试使用Go泛型比较两个类型为V的值不起作用。

huangapple go评论69阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月2日 02:58:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76596159.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定