Created
September 5, 2019 11:09
-
-
Save leopku/8f90d7e51595664c7f8dfe6d277d2afc to your computer and use it in GitHub Desktop.
Dynamic create struct in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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