36-golang动态创建类
动态创建类
(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
    
【励志篇】:
古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号