使用定义的类型而不是类型文字的递归类型约束?

Mar*_*ský 2 generics recursion interface go

在 Go2 泛型中,截至当前草案,我可以使用接口指定泛型类型的类型约束。

import "fmt"

type Stringer interface {
    String() string
}

func Print[T Stringer](value T) {
    fmt.Println(value.String())
}
Run Code Online (Sandbox Code Playgroud)

这样,我可以指定该类型必须实现一个方法。但是,我没有看到任何方法可以强制执行方法,该方法本身具有泛型类型的参数。

type Lesser interface {
    Less(rhs Lesser) bool
}

type Int int

func (lhs Int) Less(rhs Int) bool {
    return lhs < rhs
}

func IsLess[T Lesser](lhs, rhs T) bool {
    return lhs.Less(rhs)
}

func main() {
    IsLess[Int](Int(10), Int(20))
}
Run Code Online (Sandbox Code Playgroud)

退出时

Int does not satisfy Lesser: wrong method signature
    got  func (Int).Less(rhs Int) bool
    want func (Lesser).Less(rhs Lesser) bool
Run Code Online (Sandbox Code Playgroud)

带有合同的原始草案将使这成为可能,但新草案则不然。

也可以通过以下方式完成,但这会让您一遍又一遍地重复相同的约束,从而阻止 DRY(DRY 代码是泛型的目的)。如果所需的接口有多个方法,它也会使代码变得更加笨拙。

Int does not satisfy Lesser: wrong method signature
    got  func (Int).Less(rhs Int) bool
    want func (Lesser).Less(rhs Lesser) bool
Run Code Online (Sandbox Code Playgroud)

有没有办法通过新草案中的预定义接口来做到这一点?

jub*_*0bs 5

定义接口类型Lesser和功能Isless如下:

type Lesser[T any] interface {
    Less(T) bool
}

func IsLess[T Lesser[T]](x, y T) bool {
    return x.Less(y)
}
Run Code Online (Sandbox Code Playgroud)

然后,以下代码可以正常编译:

type Apple int

func (a Apple) Less(other Apple) bool {
    return a < other
}

type Orange int

func (o Orange) Less(other Orange) bool {
    return o < other
}

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 implement 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
}
Run Code Online (Sandbox Code Playgroud)

游乐场


约束T Lesser[T]可以读作

任何T具有Less(T) bool方法的类型。

我的两种自定义类型,

  • Apple及其Less(Apple) bool方法,并且
  • Orange以其Less(Orange) bool方法,

满足这个要求。

作为信息,Java 泛型允许通过所谓的递归类型绑定实现类似的技巧。有关此主题的更多信息,请参阅 Josh Bloch 的《Effective Java》第 3 版中的第 30 项(尤其是第 137-8 页)。


全面披露:当我在Gophers Slack上看到Vasko Zdravevski类似问题的解决方案时,我想起了这个悬而未决的问题。