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

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

Constraining argument of interface method to a few allowed structs?

问题

假设我有一个接口:

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

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

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

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

英文:

Suppose I have an interface :

  1. type Module interface {
  2. Run(moduleInput x) error // x is the type of moduleInput
  3. }

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

使用一个通用接口,限制为你想要限制的类型的并集:

  1. // 接口约束
  2. type Inputs interface {
  3. moduleAInputs | moduleBInputs
  4. }
  5. // 参数化接口
  6. type Module[T Inputs] interface {
  7. Run(moduleInput T) error
  8. }

请注意,接口 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:

  1. // interface constraint
  2. type Inputs interface {
  3. moduleAInputs | moduleBInputs
  4. }
  5. // parametrized interface
  6. type Module[T Inputs] interface {
  7. Run(moduleInput T) error
  8. }

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:

确定