如何在接口方法中使用类型参数?

Pri*_*jan 9 generics interface go

我正在尝试编写一个示例程序来尝试使用 Go 泛型来实现数据结构。

作为其中的一部分,我想定义一个迭代器接口。我有以下代码:

package collection

type Iterator interface {
    ForEachRemaining(action func[T any](T) error) error
    // other methods
}

Run Code Online (Sandbox Code Playgroud)

它一直给我以下错误

函数类型不能有类型参数

将类型参数移至方法也不起作用:

type Iterator interface {
    ForEachRemaining[T any](action func(T) error) error
    // other methods
}
Run Code Online (Sandbox Code Playgroud)

给出错误:

方法不能有类型参数

有没有办法定义通用接口

May*_*tel 24

正如错误所暗示的那样,methods cannot have type parameters根据最新的设计,他们自己的。但是,它们可以使用它们所属的接口或结构中的泛型。

您需要在接口类型上指定类型参数,如下所示:

type Iterator[T any] interface {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

然后将 用作T接口体内方法中的任何其他类型参数。例如:

type Iterator[T any] interface {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

在Go Playground上尝试一下。