假设我有一个界面:
type Module interface {
Run(moduleInput x) error // x is the type of moduleInput
}
其中每个“模块”将实现Run
功能。但是,moduleInput
不是单个结构 - 它应该能够接受任何结构,但只能接受允许的结构,即不是 interface{}
(例如,仅 moduleAInputs
和 moduleBInputs
结构)。
理想情况下,每个模块的 Run
函数的类型为 moduleXInput
,其中 X 是示例模块。
是否可以使用泛型或其他方式约束 moduleInput
的类型?
最佳答案
使用通用接口(interface),限制为您想要限制的类型的联合:
// interface constraint
type Inputs interface {
moduleAInputs | moduleBInputs
}
// parametrized interface
type Module[T Inputs] interface {
Run(moduleInput T) error
}
请注意,接口(interface) Module[T]
现在可以通过其方法与该接口(interface)的实例化相匹配的类型来实现。有关此内容的全面解释,请参阅:How to implement generic interfaces?
关于go - 将接口(interface)方法的参数限制为一些允许的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72989975/