动态创建类
(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
到此这篇关于golang动态创建类的文章就介绍到这了,更多相关golang动态创建类内容请搜索晓枫资讯以前的文章或继续浏览下面的相关文章希望大家以后多多支持晓枫资讯!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |