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

huangapple go评论79阅读模式
英文:

Constraining argument of interface method to a few allowed structs?

问题

假设我有一个接口:

type Module interface {
    Run(moduleInput x) error // x 是 moduleInput 的类型
}

每个"module"都将实现Run函数。然而,moduleInput不是一个单一的结构体 - 它应该能够接受任何结构体,但只允许特定的结构体,即不是interface{}(比如,只有moduleAInputsmoduleBInputs结构体)。

理想情况下,每个模块的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

huangapple
  • 本文由 发表于 2022年7月15日 14:44:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/72989975.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定