函数类型不能有类型参数
Function type cannot have type parameters
我正在尝试编写一个示例程序来尝试使用 go2 中提出的 go generic 实现数据结构。
作为其中的一部分,我想定义一个迭代器接口。我有以下代码:
package collection
type Iterator interface {
//ForEachRemaining Performs the given action for each remaining element until all elements have been processed or
//the action throws an error.
ForEachRemaining(action func[T any](T) error) error
//HasNext returns true if the iteration has more elements.
HasNext() bool
//Next returns the next element in the iteration.
Next() error
//Remove removes from the underlying collection the last element returned by this iterator (optional operation).
Remove() error
}
它一直给我下面的错误
function type cannot have type parameters
有没有办法定义通用接口
正如错误提示的那样,methods cannot have type parameters
是他们自己的最新设计。但是,它们可以使用它们所属的接口或结构中的泛型。
你需要在接口类型上指定type参数如下:
type Iterator[T any] interface {
// ...
}
然后在接口体内的方法中使用 T
作为任何其他类型参数。例如:
package main
import "fmt"
type Iterator[T any] interface {
ForEachRemaining(action func(T) error) error
// other methods
}
func main() {
fmt.Println("This program compiles")
}
在 Go playground 上试用。
我正在尝试编写一个示例程序来尝试使用 go2 中提出的 go generic 实现数据结构。
作为其中的一部分,我想定义一个迭代器接口。我有以下代码:
package collection
type Iterator interface {
//ForEachRemaining Performs the given action for each remaining element until all elements have been processed or
//the action throws an error.
ForEachRemaining(action func[T any](T) error) error
//HasNext returns true if the iteration has more elements.
HasNext() bool
//Next returns the next element in the iteration.
Next() error
//Remove removes from the underlying collection the last element returned by this iterator (optional operation).
Remove() error
}
它一直给我下面的错误
function type cannot have type parameters
有没有办法定义通用接口
正如错误提示的那样,methods cannot have type parameters
是他们自己的最新设计。但是,它们可以使用它们所属的接口或结构中的泛型。
你需要在接口类型上指定type参数如下:
type Iterator[T any] interface {
// ...
}
然后在接口体内的方法中使用 T
作为任何其他类型参数。例如:
package main
import "fmt"
type Iterator[T any] interface {
ForEachRemaining(action func(T) error) error
// other methods
}
func main() {
fmt.Println("This program compiles")
}
在 Go playground 上试用。