根据结构体名字获取结构体对象
2019-06-22 本文已影响0人
yanjusong
package main
import (
"fmt"
"reflect"
)
type Foo struct {
FooID int
}
type Bar struct {
BarID int
}
func init() {
structMap = make(map[string]interface{})
structMap["Foo"] = Foo{}
structMap["Bar"] = Bar{}
}
// 用于保存实例化的结构体对象
var structMap map[string]interface{}
func getObj(structName string) interface{} {
if i, ok := structMap[structName]; ok {
t := reflect.TypeOf(i)
return reflect.New(t)
}
return nil
}
func main() {
b := getObj("Bar")
fmt.Printf("%+v\n", b)
f := getObj("Foo")
fmt.Printf("%+v\n", f)
none := getObj("hello")
fmt.Printf("%+v\n", none)
}