Home > Back-end >  Constraining argument of interface method to a few allowed structs?
Constraining argument of interface method to a few allowed structs?

Time:07-16

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?

CodePudding user response:

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: How to implement generic interfaces?

  • Related