打赏

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

posted @   苍山落暮  阅读(87)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示