英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论