golang 动态 实例化 结构体

在Go语言中,由于其静态类型特性,直接通过类型名字符串创建对象并不容易。可以使用全局映射表结合反射来实现,例如在init函数中初始化包含所有可发现类型的映射。通过`reflect.Type`获取类型并用`reflect.New`创建对象。但这种方法可能引入更多错误,考虑使用工厂方法或函数映射。注意,映射仅适用于没有输入参数和返回值的函数原型,若要处理不同函数原型,可能需要使用interface{}。
摘要由CSDN通过智能技术生成


真理 http://stackoverflow.com/questions/10210188/instance-new-type-golang

So, if I understand your question correctly, you are asking about how you can create an object when you just have the name of the type as string. So, for example, you might have a string "MyStruct" and you want to create an object of this type.

Unfortunately, that's not easily possible because Go is a statically typed language and the linker will eliminate dead code (or inline parts of it). So, there is no guarantee, that your final executable will even contain the code of "MyStruct".

You can however, maintain a global map[string]reflect.Type manually. For example by initializing this map in the init() function of your packages which defines such discover-able types. This will also tell the compiler that you are using the types. Afterwards, you can use this map to look up the reflect.Type of the type you want to create and use reflect.New to get a pointer to a new object of that type (stored as a reflect.Value). You can extract the object into an interface with something like this:

reflect.New
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值