找到接口的所有实现并将它们放入一个切片中。

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

Find all implementations of interface and put them in a slice

问题

我正在尝试实现一个类似这样的 Golang 插件接口:

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()
    }
}

我可以调用在 plugins 切片中定义的所有插件。切片中的项是硬编码的,有没有办法自动生成切片呢?

英文:

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?

答案1

得分: 2

一种常见的做法是创建一个注册函数,并在包的init()函数中调用该函数。具体代码如下:

var plugins = []Plugin{}

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

在声明插件的包中,可以这样使用:

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

只有在导入声明插件的所有包之后,插件才会被填充。

英文:

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.

huangapple
  • 本文由 发表于 2021年9月21日 11:21:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/69262993.html
匿名

发表评论

匿名网友

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

确定