'How to pass various related types to a common helper function? [duplicate]

I am writing a home monitoring program that consist of plugins that are functions executing specific checks. Each plugin has a specific input (dependent on the nature of the check) and a response common to all plugins.

An example of the main types involved could be:

// PluginHTTPBasicStruct describes the configuration of a simple HTTP check (connection to a web server)
type PluginHTTPBasicStruct struct {
    Host          string
    ExpectedCodes []int
}

// PluginResponse describes the response of all plugins
type PluginResponse struct {
    OK   bool
    When time.Time
    Why  string
}

func PluginHTTPBasic(target PluginHTTPBasicStruct) PluginResponse {
  // checks happen here 
}

In that simple program, I would like to run a series of calls to a single runPlugin helper function, such as

runPlugin(PluginHTTPBasic, PluginHTTPBasicStruct{
        Host:          "one.example.com",
        ExpectedCodes: [200],
    })

Now, my goal is to have runPlugin take a first parameter which is a function, and a struct of any type (I will think about constraints later).

To this, I thought about using the following code:

// PluginInputsAll will list all possible inputs
type PluginInputsAll interface {
    PluginHTTPBasicStruct
}
type PluginFunction[T PluginInputsAll] func(T)
type PluginInput[T PluginInputsAll] T

func runPlugin(plugin PluginFunction, input PluginInput) {
    resp := plugin(input)
    log.Info().Msg(resp)
}

How can I structure such a generic function?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source