英文:
Constraining argument of interface method to a few allowed structs?
问题
假设我有一个接口:
type Module interface {
Run(moduleInput x) error // x 是 moduleInput 的类型
}
每个"module"都将实现Run
函数。然而,moduleInput
不是一个单一的结构体 - 它应该能够接受任何结构体,但只允许特定的结构体,即不是interface{}
(比如,只有moduleAInputs
和moduleBInputs
结构体)。
理想情况下,每个模块的Run
函数应该具有moduleXInput
类型,其中X是一个示例模块。
是否可以使用泛型或其他方式限制moduleInput
的类型?
英文:
Suppose I have an interface :
type Module interface {
Run(moduleInput x) error // x is the type of moduleInput
}
where each "module" will fulfill the Run
function. However, the moduleInput
isn't a single struct - it should be able to accept any struct but only allowed structs, i.e not interface{}
(say, only moduleAInputs
and moduleBInputs
struct).
Ideally the Run
function for each module would have the type of moduleXInput
where X is an example module.
Is it possible to constrain the type of moduleInput
with generics or otherwise?
答案1
得分: 5
使用一个通用接口,限制为你想要限制的类型的并集:
// 接口约束
type Inputs interface {
moduleAInputs | moduleBInputs
}
// 参数化接口
type Module[T Inputs] interface {
Run(moduleInput T) error
}
请注意,接口 Module[T]
现在可以由方法与该接口的实例化匹配的类型来实现。有关此的详细解释,请参阅:https://stackoverflow.com/questions/72034479/how-to-implement-generic-interfaces
英文:
Use a generic interface, constrained to the union of the types you want to restrict:
// interface constraint
type Inputs interface {
moduleAInputs | moduleBInputs
}
// parametrized interface
type Module[T Inputs] interface {
Run(moduleInput T) error
}
Note that the interface Module[T]
can now be implemented by types whose methods match the instantiation of this interface. For a comprehensive explanation of this, see: https://stackoverflow.com/questions/72034479/how-to-implement-generic-interfaces
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论