Skip to content

Instantly share code, notes, and snippets.

@leopku
Created September 5, 2019 11:09
Show Gist options
  • Save leopku/8f90d7e51595664c7f8dfe6d277d2afc to your computer and use it in GitHub Desktop.
Save leopku/8f90d7e51595664c7f8dfe6d277d2afc to your computer and use it in GitHub Desktop.
Dynamic create struct in golang
package main
import (
"fmt"
)
type Creator func() Plugin
type Plugin interface {
Pr()
}
var Plugins = map[string]Creator{}
func Add(name string, creator Creator) {
Plugins[name] = creator
}
func CreatePluginStruct(creator Creator) Plugin {
return creator()
}
func main() {
RedisInt()
name := "redis"
creator := Plugins[name]
newstruct := CreatePluginStruct(creator)
newstruct.Pr()
}
//以下是另一个文件
type Redis struct {
Name string
}
func (r Redis) Pr() {
fmt.Println(r.Name)
}
//模拟init()
func RedisInt() {
Add("redis", func() Plugin {
return &Redis{Name: "redis"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment