Home > Blockchain >  Find all implementations of interface and put them in a slice
Find all implementations of interface and put them in a slice

Time:09-22

I'm trying to implement a golang plugin interface like this:

package main

import "fmt"

type Plugin interface {
    Run() bool
}
type Plugin1 struct{}
type Plugin2 struct{}

func (p Plugin1) Run() bool {
    fmt.Println("Plugin1::Run()")
    return true
}

func (p Plugin2) Run() bool {
    fmt.Println("Plugin2::Run()")
    return true
}

func main() {
    plugins := []Plugin{
        Plugin1{},
        Plugin2{},
    }

    for _, plugin := range plugins {
        plugin.Run()
    }
}

I can invoke all the plugins defined in the plugins slice. The items in the slice is hardcoded, is there a way to generate the slice automatically?

CodePudding user response:

A common way of doing this is to have a register function, and call that function from init() functions of packages. That is:

var plugins = []Plugin{}

func RegisterPlugin(p Plugin) {
  plugins=append(plugins,p)
}

In packages that declare plugins:

func init() {
   plugins.RegisterPlugin(MyPlugin{})
}

The plugins will be populated once you import all packages declaring plugins.

  • Related