动态创建类
(1.)使用反射创建类
import `reflect`
var typeRegistry = make(map[string]reflect.Type)
func RegisterType(elem interface{}) {
t := reflect.TypeOf(elem).Elem()
typeRegistry[t.Name()] = t
}
func NewStruct(name string) (interface{}, bool) {
elem, ok := typeRegistry[name]
if !ok {
return nil, false
}
return reflect.New(elem).Elem().Interface(), true
}
(2.)使用示例
// 定义结构体
type Student struct {
Name string
Age int
}
// 初始化时注册类型
func init() {
RegisterType((*Student)(nil))
}
// 获取对象
func getObj(structName string) (*Student, error) {
st, ok := NewStruct(structName)
if !ok {
return nil, errors.New("new struct not ok")
}
student, ok := st.(Student)
if !ok {
return nil, fmt.Errorf("assert st to Student error,st:%T", st)
}
// 给结构体字段赋值
student.Name = "jones"
student.Age = 18
return &student, nil
}
func main(){
// 获取一个对象
stu := getObj("Student")
fmt.Printf("stu:%+v",stu)
}
参考链接
https://blog.csdn.net/qq_41257365/article/details/114108970
https://blog.csdn.net/whatday/article/details/113773167