1 回答

TA贡献1943条经验 获得超7个赞
定义接口类型Lesser和功能Isless如下:
type Lesser[T any] interface {
Less(T) bool
}
func IsLess[T Lesser[T]](lhs, rhs T) bool {
return lhs.Less(rhs)
}
然后,以下代码可以顺利编译:
type Apple int
func (lhs Apple) Less(rhs Apple) bool {
return lhs < rhs
}
type Orange int
func (lhs Orange) Less(rhs Orange) bool {
return lhs < rhs
}
func main() {
fmt.Println(IsLess(Apple(10), Apple(20))) // true
fmt.Println(IsLess(Orange(30), Orange(15))) // false
// fmt.Println(IsLess(10, 30))
// compilation error: int does not satisfy Lesser[T] (missing method Less)
// fmt.Println(IsLess(Apple(20), Orange(30)))
// compilation error: type Orange of Orange(30) does not match inferred type Apple for T
}
(游乐场)
约束T Lesser[T]可以读作
任何T有Less(T) bool方法的类型。
我的两种自定义类型,
Apple用它的Less(Apple) bool方法,和
Orange用它的Less(Orange) bool方法,
满足这个要求。
作为信息,Java 泛型允许通过所谓的递归类型绑定来实现类似的技巧。有关此主题的更多信息,请参阅 Josh Bloch 的Effective Java第 3 版中的第 30 项(尤其是 p137-8)。
- 1 回答
- 0 关注
- 171 浏览
添加回答
举报