相关疑难解决方法(0)

如何实现通用接口?

我刚刚看到 Go 在其最新版本中合并了泛型,我正在尝试创建一个小项目来了解它是如何工作的。除了现在通用的非常简单的功能之外,我似乎不知道它是如何工作的。我希望能够做这样的事情:

type Dao[RT any] interface {
    FindOne(id string) *RT
}

type MyDao struct {
}

type ReturnType struct {
    id int
}

func (m *MyDao) FindOne(id string) *ReturnType {
    panic("implement me")
}

// how should this look like?

func NewMyDao() *Dao[ReturnType] {
    return &MyDao[ReturnType]{}
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?我似乎没有以这种方式实现接口,并且我已经尝试了许多相同的组合。

有没有办法实现通用接口?如果不是,是否只能返回类型interface{}

generics interface go

34
推荐指数
2
解决办法
5万
查看次数

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

我正在尝试编写一个示例程序来尝试使用 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)

给出错误:

方法不能有类型参数

有没有办法定义通用接口

generics interface go

9
推荐指数
1
解决办法
1万
查看次数

标签 统计

generics ×2

go ×2

interface ×2