我正在尝试编写一个示例程序来尝试使用 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)
给出错误:
方法不能有类型参数
有没有办法定义通用接口
如何为结构创建对象?
object := new(struct)
Run Code Online (Sandbox Code Playgroud)
要么
var object struct
Run Code Online (Sandbox Code Playgroud)
我无法理解什么时候使用什么?如果两者相同哪一个应该优先?