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

假设我有一个接口:


type Module interface {

    Run(moduleInput x) error // x is the type of moduleInput

}

每个“模块”都将实现Run功能。然而,这moduleInput不是一个单一的结构——它应该能够接受任何结构但只允许结构,即不是interface{}(比如,只有moduleAInputs和moduleBInputs结构)。


理想情况下Run,每个模块的函数都具有moduleXInputX 是示例模块的类型。


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


暮色呼如
浏览 81回答 1
1回答

呼啦一阵风

使用通用接口,限制为要限制的类型的联合:// interface constrainttype Inputs interface {    moduleAInputs | moduleBInputs}// parametrized interfacetype Module[T Inputs] interface {    Run(moduleInput T) error}请注意,该接口Module[T]现在可以由其方法与该接口的实例化相匹配的类型来实现。有关对此的全面解释,请参阅:如何实现通用接口?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go