假设我有一个接口:

type Module interface {
    Run(moduleInput x) error // x is the type of moduleInput
}

其中每个"模块"将实现Run功能.然而,moduleInput不是单个 struct -它应该能够接受任何 struct ,但只能接受允许的 struct ,即不是interface{}(例如,只有moduleAInputsmoduleBInputs struct ).

理想情况下,每个模块的Run函数的类型为moduleXInput,其中X是一个示例模块.

是否可以用泛型或其他方式约束moduleInput的类型?

推荐答案

使用通用接口,约束到要限制的类型的并集:

// interface constraint
type Inputs interface {
    moduleAInputs | moduleBInputs
}

// parametrized interface
type Module[T Inputs] interface {
    Run(moduleInput T) error
}

注意,接口Module[T]现在可以通过其方法与instantiation of this interface匹配的类型来实现.有关这方面的全面解释,请参阅:How to implement generic interfaces?

Go相关问答推荐

try 用GitHub操作中的release标签更新version. go文件,但失败了

调用API时使用nginx作为反向代理时从nginx获取502坏网关

Golang中的泛型 struct /接口列表

如何使用Gio设置标题栏图标

我找不到pcap.Openlive的设备名称

Azure golang SDK - 将 AcrPull 角色分配给 AKS 群集

从带有嵌套括号的字符串中提取值

Github Actions Go lambda 项目不同的 sha256sums

如何将元素从一个切片移动到另一个切片

为什么 `append(x[:0:0], x...)` 将切片复制到 Go 中的新后备数组中?

将 []float64 像素切片转换为图像

Golang prometheus 显示自定义指标

不理解切片和指针

如何允许可转换为指针的泛型类型参数化另一种可转换为指针的泛型类型?

手动下载并放置一个 golang mod 文件

如何使用 fyne 避免 GUI 应用程序中的循环依赖?

如何将类型转换为字节数组golang

在 etcd 键值存储中禁用历史记录

同一个 Go struct成员上的多个标签

为什么 Go 的构造函数要返回地址?