将接口方法的参数限制为一些允许的结构?

JC1*_*JC1 2 generics methods go

假设我有一个界面:

type Module interface {
    Run(moduleInput x) error // x is the type of moduleInput
}
Run Code Online (Sandbox Code Playgroud)

其中每个“模块”将完成该Run功能。但是,它moduleInput不是单个结构 - 它应该能够接受任何结构,但只接受允许的结构,即不接受interface{}(例如,仅moduleAInputsmoduleBInputs结构)。

理想情况下,Run每个模块的函数都具有以下类型,moduleXInput其中 X 是示例模块。

是否可以使用泛型或其他方式限制 的类型moduleInput

bla*_*een 5

使用通用接口,限制为您想要限制的类型的联合:

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

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

请注意,该接口现在可以由其方法与该接口的实例化Module[T]相匹配的类型来实现。对此的全面解释,请参见:如何实现泛型接口?