如何在 Go 中运行时根据结构的类型创建结构的新实例?
在 Go 中,如何在运行时根据对象的类型创建对象的实例?我想您还需要首先获取对象的实际类型?
我正在尝试进行惰性实例化以节省内存。
In Go, how do you create the instance of an object from its type at run time? I suppose you would also need to get the actual type
of the object first too?
I am trying to do lazy instantiation to save memory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为此,您需要
reflect
。您可以使用结构类型而不是 int 执行相同的操作。或者其他什么,真的。当涉及到映射和切片类型时,请务必了解 new 和 make 之间的区别。
In order to do that you need
reflect
.You can do the same thing with a struct type instead of an int. Or anything else, really. Just be sure to know the distinction between new and make when it comes to map and slice types.
由于reflect.New不会自动创建结构体字段中使用的引用类型,因此您可以使用类似以下内容的方法来递归地初始化这些字段类型(请注意本例中的递归结构体定义):
As
reflect.New
doesn't automatically make reference types used in struct fields, you could use something like the following to recursively initialize those field types (note the recursive struct definition in this example):您可以使用reflect.Zero()它将返回结构类型零值的表示形式。 (与
var foo StructType
类似)这与reflect.New()
不同,因为后者会动态分配结构并为您提供一个指针,类似于 <代码>新(结构类型)You can use
reflect.Zero()
which will return the representation of the zero value of the struct type. (similar to if you didvar foo StructType
) This is different fromreflect.New()
as the latter will dynamically allocate the struct and give you a pointer, similar tonew(StructType)
这是 Evan Shaw 给出的一个基本示例,但有一个结构:
根据 newacct 的响应,使用 Reflect.zero 它将是:
这是一篇关于 Go 反射基础知识的精彩文章。
Here's a basic example like Evan Shaw gave, but with a struct:
Per newacct's response, using Reflect.zero it would be:
This is a great article on the basics of reflection in go.
您不需要
reflect
并且如果它们共享相同的接口,您可以使用工厂模式轻松完成此操作:You don't need
reflect
and you can do this easy with factory pattern if they share the same interface:自己偶然发现了相同(或非常相似)的问题。这是几个小时实验的结果,无论它是否是指针,都会进行结构类型复制的解决方案:
注意 - 不是深层复制 - 只是一个新实例,即一个空对象,就像你初始化它一样你自己。这正是反序列化/解组目标所需要的。
完整演示:https://go.dev/play/p/vHFViKJZlV9
Stumbled myself on to the same (or very similar) problem. Here's the result of few hours' experiments, the solution that makes a struct type copy, no matter whether it is a pointer or not:
Note - not a deep copy - just a new instance, i.e. an empty object, as if you inited it yourself. That's exactly what is wanted as a deserialization/unmarshalling target.
The full demo: https://go.dev/play/p/vHFViKJZlV9