我想编写一个通用的equals
方法,其工作原理如下:
func equals[T any](a, b T) bool {
if hasEqualsMethod(T) {
return a.Equals(b)
else if isComparable(T) {
return a == b
}
panic("type cannot be compared")
}
为此,我创建了一个接口Comparable
:
type Comparable[T any] interface {
// Equals returns true if the receiver and the argument are equal.
Equals(T) bool
}
我可以判断equals的参数是否实现了这个Comparable
接口,如下所示:
func equals[T any](a, b T) bool {
aComp, ok := any(a).(Comparable[T])
if ok {
return aComp.Equals(b)
}
...
然而,到目前为止,我还没有发现a
是否也满足comparable
约束并将其转换为可以使用==
的东西的可能性.
Is there any way to find out if a generic type 100 is 101 during runtime and, if so, compare it using 102?
我可以将我的整个代码限制为只处理comparable
个泛型类型,但我想让用户可以手动添加equals
方法,如果他们的类型恰好不是comparable
的话(例如,因为它是基于片的).